From b527b5062a64b87b7bd2130b4b4351fba35d40e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 13:44:48 -0700 Subject: [PATCH 1/8] Save the flattened document at full size into .pcraft files as an option A .pcraft bundle holds the flattened document only as thumb.png (at most 256 px) and composite/preview.png (at most 1024 px). A new option also writes composite/full.png: the flattened document at its canvas size, an 8-bit RGBA PNG made like the two previews, with the ICC profile of its pixels embedded. The option is off by default, and a save without it writes the same bytes as before. - Preferences > File Handling > Save Full-Size Composite in .pcraft Files sets it for the app's Save, Save As and Save a Copy, in the desktop and web builds. - The engine's file.saveACopy and its batch and export commands take "pcraftFullComposite" (unset, the preference), the automation doc.save and MCP doc_save take "pcraftFullComposite": true, and photocraft-cli convert, run and batch take --pcraft-full-composite. The manifest names the image in a new optional member, full_composite; the format version stays 1, and bundles without it open as before. A canvas over 2^30 pixels, or one whose pixels cannot be allocated, is saved without it, and so is a ZIP bundle that it would take past 4 GiB or 65,535 entries. --- apps/photocraft-cli/src/args.rs | 4 + apps/photocraft-cli/src/output.rs | 2 +- apps/photocraft-cli/tests/it/cli.rs | 20 ++ book/src/formats/pcraft.md | 5 + crates/automation/src/files.rs | 17 +- crates/automation/src/rpc.rs | 8 +- crates/automation/src/server.rs | 8 +- crates/automation/tests/it/main.rs | 1 + .../tests/it/native_full_composite.rs | 45 +++++ crates/engine/src/cmd/file_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/save.rs | 12 +- crates/engine/src/cmd/file_cmds/tests.rs | 22 +++ crates/engine/src/prefs.rs | 4 + crates/format/src/lib.rs | 6 + crates/format/src/manifest.rs | 3 + crates/format/src/store.rs | 187 ++++++++++++++---- crates/format/tests/it/roundtrip.rs | 38 +++- crates/io/src/lib.rs | 67 ++++++- crates/io/src/psd_thumbnail.rs | 2 +- crates/io/tests/it/main.rs | 1 + crates/io/tests/it/pcraft_full_composite.rs | 131 ++++++++++++ crates/ui-egui/src/app/files.rs | 10 +- crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/prefs/prefs_ui/fields.rs | 3 + crates/ui-egui/src/save_identity_tests.rs | 23 +++ crates/ui-egui/src/services.rs | 5 + docs/control-protocol.md | 2 +- docs/development.md | 1 + docs/scorecard.md | 4 +- 48 files changed, 592 insertions(+), 61 deletions(-) create mode 100644 crates/automation/tests/it/native_full_composite.rs create mode 100644 crates/io/tests/it/pcraft_full_composite.rs diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 91b99ef33b9..66e2fbb3d7c 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -74,6 +74,10 @@ pub(crate) struct ExportArgs { /// and CMYK shrink) or progressive #[arg(long, value_name = "baseline|optimized|progressive", value_parser = jpeg_format)] pub(crate) jpeg_format: Option, + /// Also write the flattened document at its canvas size into .pcraft output, as + /// composite/full.png + #[arg(long)] + pub(crate) pcraft_full_composite: bool, } /// Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …) diff --git a/apps/photocraft-cli/src/output.rs b/apps/photocraft-cli/src/output.rs index 34101c9ec06..831258b3155 100644 --- a/apps/photocraft-cli/src/output.rs +++ b/apps/photocraft-cli/src/output.rs @@ -8,7 +8,7 @@ use crate::{Result, args::ExportArgs}; impl From<&ExportArgs> for ExportOptions { fn from(a: &ExportArgs) -> Self { // TIFF output is flat unless asked: scripted conversions keep predictable sizes. - let mut o = ExportOptions { tiff_layers: a.tiff_layers, tga_bits: a.tga_bits, ..Default::default() }; + let mut o = ExportOptions { tiff_layers: a.tiff_layers, tga_bits: a.tga_bits, pcraft_full_composite: a.pcraft_full_composite, ..Default::default() }; if let Some(q) = a.quality { o.encode.jpeg_quality = q; // Asking for a quality asks for a lossy WebP; the default WebP stays lossless. diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 2c06a488fd4..348106b7e7f 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -1025,6 +1025,26 @@ fn tiff_output_is_flat_unless_tiff_layers_is_given() { std::fs::remove_dir_all(d).unwrap(); } +#[test] +fn pcraft_output_has_no_full_composite_unless_asked() { + let d = tmp("pcraft-full-composite"); + let full = |path: &std::path::Path| photocraft_format::read_manifest(&std::fs::read(path).unwrap()).unwrap().full_composite.is_some(); + for (name, flag, expect) in [("plain.pcraft", None, false), ("full.pcraft", Some("--pcraft-full-composite"), true)] { + let out = d.join(name); + let mut cmd = bin(); + cmd.args(["run", "--new", r#"{"width":16,"height":16}"#]); + if let Some(flag) = flag { + cmd.arg(flag); + } + ok(cmd.arg("--out").arg(&out)); + assert_eq!(full(&out), expect, "{name}"); + } + let converted = d.join("converted.pcraft"); + ok(bin().arg("convert").arg(d.join("plain.pcraft")).arg(&converted).arg("--pcraft-full-composite")); + assert!(full(&converted)); + std::fs::remove_dir_all(d).unwrap(); +} + /// Issue #1108: a non-Unicode argument (a Latin-1 file name on Linux) used to panic in /// `std::env::args()` before anything was printed. clap reads the arguments as they are: a path /// takes one, and text (`--filter`) refuses it with a usage error. diff --git a/book/src/formats/pcraft.md b/book/src/formats/pcraft.md index 40ecbdd1271..46a3dc553ca 100644 --- a/book/src/formats/pcraft.md +++ b/book/src/formats/pcraft.md @@ -8,9 +8,14 @@ tiles/.zst blobs/.zst thumb.png composite/preview.png +composite/full.png save.lock ``` +`thumb.png` (at most 256 px on the longer side), `composite/preview.png` (at most 1024 px) and `composite/full.png` (the canvas size) are the flattened document as 8-bit RGBA PNGs, whatever the document's depth. The manifest names each one it holds, under `thumbnail`, `composite` and `full_composite`. + +A save writes `composite/full.png` only when it is asked to: *Save Full-Size Composite in .pcraft Files* in Preferences › File Handling for the app's saves, `"pcraftFullComposite": true` for the engine's `file.saveACopy` and its batch and export commands, and for the automation `doc.save` and MCP `doc_save`, and `--pcraft-full-composite` for `photocraft-cli convert`, `run` and `batch`. It is off by default. `composite/full.png` embeds the ICC profile of its pixels: an RGB document's own profile, a grayscale document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable profile. A save leaves it out when the canvas is larger than 2^30 pixels, when its pixels cannot be allocated, or when a ZIP bundle would pass 4 GiB or 65,535 entries with it. A directory bundle saved without it has the file from an earlier save removed. + `save.lock` exists only in directory bundles: a save holds an OS file lock on it while it writes objects, publishes the manifest and removes unreferenced objects, so concurrent saves of one bundle take turns. It is empty, and readers ignore it. The manifest is versioned and describes the document tree. Tiles and blobs are content-addressed. Loaders verify ZIP entry bounds and CRCs; document content also uses stored hashes to detect mismatched or corrupted tile/blob content. Unsupported newer format versions fail explicitly. diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index 0b8ff103aa6..5f509a692c5 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -54,7 +54,18 @@ pub fn open(path: &Path) -> Result { /// Previews for a `.pcraft` bundle. pub fn previews(doc: &Document) -> SaveOptions { - SaveOptions { thumbnail: Some(photocraft_compose::thumbnail(doc, 256)), composite: Some(photocraft_compose::thumbnail(doc, 1024)) } + SaveOptions { thumbnail: Some(photocraft_compose::thumbnail(doc, 256)), composite: Some(photocraft_compose::thumbnail(doc, 1024)), ..Default::default() } +} + +/// [`previews`], plus the full-size composite when `opts` asks for it +/// ([`ExportOptions::pcraft_full_composite`]). +fn native_options(doc: &Document, opts: &ExportOptions) -> SaveOptions { + let mut out = previews(doc); + if opts.pcraft_full_composite { + out.full_composite = photocraft_io::pcraft_full_composite(doc); + out.full_composite_icc = out.full_composite.as_ref().map(|_| photocraft_io::pcraft_full_composite_icc(doc)); + } + out } /// Encode the name the saved native bundle will report on reopening. Save As updates @@ -86,7 +97,7 @@ pub fn save( let named = named_for_output(doc, &path.to_string_lossy()); let mut local = PcraftWriter::new(); let w = writer.unwrap_or(&mut local); - w.save_path(&named, path, &previews(&named))?; + w.save_path(&named, path, &native_options(&named, opts))?; return Ok(Vec::new()); } let r = photocraft_io::export(doc, &ext, opts)?; @@ -104,7 +115,7 @@ pub fn save_bytes(doc: &Document, name: &str, format_override: Option<&str>, opt .ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{name}`; pass a format")))?; if ext == photocraft_format::EXTENSION { let named = named_for_output(doc, name); - return Ok((photocraft_format::save_to_bytes(&named, &previews(&named))?, Vec::new())); + return Ok((photocraft_format::save_to_bytes(&named, &native_options(&named, opts))?, Vec::new())); } let result = photocraft_io::export(doc, &ext, opts)?; Ok((result.bytes, result.warnings)) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 98ccc9a24a3..db0807fb247 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -123,8 +123,12 @@ impl Headless { "doc.new" => self.command_run("file.new", p), "doc.save" => { let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; - let mut opts = - photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, ..Default::default() }; + let mut opts = photocraft_io::ExportOptions { + tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), + tga_bits, + pcraft_full_composite: p.get("pcraftFullComposite").and_then(Value::as_bool).unwrap_or(false), + ..Default::default() + }; opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default(); match p.get("quality") { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 61a6454e79d..11acba25d9c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -191,6 +191,10 @@ pub struct SaveParams { /// DDS: also write the full mip chain, each level a box filter of the one above. #[serde(default, rename = "ddsMipmaps")] pub dds_mipmaps: bool, + /// .pcraft: also write the flattened document at its canvas size as `composite/full.png`. + /// Off by default. + #[serde(default, rename = "pcraftFullComposite")] + pub pcraft_full_composite: bool, #[serde(default)] pub index: Option, } @@ -1077,6 +1081,7 @@ impl PhotocraftMcp { p.format.is_some().then_some("format"), p.quality.is_some().then_some("quality"), p.tiff_layers.then_some("tiffLayers"), + p.pcraft_full_composite.then_some("pcraftFullComposite"), dpx_bits.is_some().then_some("dpxBits"), p.index.is_some().then_some("index"), ] @@ -1103,7 +1108,8 @@ impl PhotocraftMcp { } let Some(r) = self .headless_op(move |h| { - let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, ..Default::default() }; + let mut opts = + photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, pcraft_full_composite: p.pcraft_full_composite, ..Default::default() }; opts.encode.dpx_bits = dpx_bits; opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; if let Some(q) = p.quality { diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index f701bd705ba..0fdd94a4a86 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -10,6 +10,7 @@ mod layered_save_dirty; mod mcp; mod mcp_wire; mod missing_font_warnings; +mod native_full_composite; mod native_save_name; mod openraster; mod raw_defaults; diff --git a/crates/automation/tests/it/native_full_composite.rs b/crates/automation/tests/it/native_full_composite.rs new file mode 100644 index 00000000000..fea554c19d1 --- /dev/null +++ b/crates/automation/tests/it/native_full_composite.rs @@ -0,0 +1,45 @@ +//! Scripted `.pcraft` saves write the full-size composite when they ask for it +//! (`pcraftFullComposite`), and leave it out by default, as the app's Save does. + +use photocraft_automation::{Headless, files}; +use photocraft_format::zip::ZipReader; +use serde_json::json; + +fn full_composite(bytes: &[u8]) -> ((u32, u32), Vec) { + let path = photocraft_format::read_manifest(bytes).unwrap().full_composite.expect("the manifest names the full-size composite"); + let png = ZipReader::new(bytes).unwrap().read_by_name(&path, usize::MAX).unwrap(); + let image = photocraft_codecs::decode(&png).unwrap(); + (image.dimensions(), image.to_rgba8()) +} + +fn has_full_composite(bytes: &[u8]) -> bool { + photocraft_format::read_manifest(bytes).unwrap().full_composite.is_some() || ZipReader::new(bytes).unwrap().find("composite/full.png").is_some() +} + +#[test] +fn scripted_native_saves_write_the_full_size_composite_when_asked() { + let dir = std::env::temp_dir().join(format!( + "pc-native-full-composite-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut headless = Headless::trusted_local(); + headless.handle("doc.new", json!({"width": 40, "height": 30, "name": "Full"})).unwrap(); + headless.handle("engine.execute", json!({"command":"image.adjustments.invert", "params":{}})).unwrap(); + let doc = headless.session.active().unwrap().doc.clone(); + let flattened = photocraft_compose::render(&doc, doc.bounds()).to_rgba8().pixels; + + let (bytes, _) = files::save_bytes(&doc, "Full.pcraft", None, &Default::default()).unwrap(); + assert!(!has_full_composite(&bytes), "off by default"); + let on = photocraft_io::ExportOptions { pcraft_full_composite: true, ..Default::default() }; + let (bytes, _) = files::save_bytes(&doc, "Full.pcraft", None, &on).unwrap(); + assert_eq!(full_composite(&bytes), ((40, 30), flattened.clone())); + + let path = dir.join("Full.pcraft"); + headless.handle("doc.save", json!({"path": path.to_str().unwrap()})).unwrap(); + assert!(!has_full_composite(&std::fs::read(&path).unwrap()), "off by default"); + headless.handle("doc.save", json!({"path": path.to_str().unwrap(), "pcraftFullComposite": true})).unwrap(); + assert_eq!(full_composite(&std::fs::read(&path).unwrap()), ((40, 30), flattened)); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index efdd3ad8bff..8291b061ffc 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -241,7 +241,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: also write the flattened document at its canvas size as composite/full.png; unset, Preferences › File Handling)}"##, native_doc, save_a_copy ), diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index 25104a7b13f..c1175624650 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -9,7 +9,8 @@ pub fn tiff_would_write_layers(doc: &Document) -> bool { } /// What a headless save writes beyond the format: JPEG quality and format, TIFF layers, Targa -/// bits, DPX bits, DDS compression and mipmaps, PSD previews and the PSD merged image. +/// bits, DPX bits, DDS compression and mipmaps, PSD previews, the PSD merged image and the +/// `.pcraft` full-size composite. #[derive(Debug, Clone, Copy)] pub(crate) struct SaveOpts { /// Photoshop's 0–12 JPEG scale. @@ -33,6 +34,9 @@ pub(crate) struct SaveOpts { /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB /// File Compatibility). pub psd_maximize_compatibility: bool, + /// `.pcraft`: also write the full-size composite (`"pcraftFullComposite"`; unset, Preferences › + /// File Handling › Save Full-Size Composite in .pcraft Files, off by default). + pub pcraft_full_composite: bool, } impl Default for SaveOpts { @@ -47,6 +51,7 @@ impl Default for SaveOpts { dds: photocraft_io::DdsOptions::default(), image_previews: true, psd_maximize_compatibility: true, + pcraft_full_composite: false, } } } @@ -56,7 +61,8 @@ impl SaveOpts { /// `jpegFormat` it doesn't name or a `tgaBits` other than 24 or 32 is an error); the image /// previews and the PSD merged image from the session's File Handling preferences (Ask When /// Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox and its - /// Maximize Compatibility checkbox both start on). + /// Maximize Compatibility checkbox both start on). The `.pcraft` full-size composite comes from + /// `pcraftFullComposite`, or without it from the File Handling preference. pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result { let file_handling = &s.prefs().file_handling; Ok(SaveOpts { @@ -69,6 +75,7 @@ impl SaveOpts { dds: dds_param(p, cmd)?.unwrap_or_default(), image_previews: file_handling.image_previews != crate::prefs::Ask::Never, psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, + pcraft_full_composite: p.get("pcraftFullComposite").and_then(Value::as_bool).unwrap_or(file_handling.pcraft_full_composite), }) } @@ -178,6 +185,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R tga_bits: save.tga_bits, image_previews: save.image_previews, psd_maximize_compatibility: save.psd_maximize_compatibility, + pcraft_full_composite: save.pcraft_full_composite, // Linked files a PSD embeds are resolved against the document being worked on. document_path: crate::doc_path::current(), // An untrusted session's stored paths are document data: embed none of them. diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 7eb770d844c..eae4793d915 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -456,6 +456,28 @@ fn maximize_compatibility_preference_controls_the_psd_merged_image() { } } +/// Preferences › File Handling › Save Full-Size Composite in .pcraft Files decides whether a +/// `.pcraft` save writes `composite/full.png` (off by default); a command's +/// `"pcraftFullComposite"` overrides it. +#[test] +fn full_composite_preference_controls_the_pcraft_full_size_composite() { + let dir = tmp("full-composite"); + let mut s = session(300, 200, 16); + let full = |path: &str| photocraft_format::read_manifest(&std::fs::read(path).unwrap()).unwrap().full_composite.is_some(); + let out = join(&dir, "default.pcraft"); + s.execute("file.saveACopy", json!({"path": out})).unwrap(); + assert!(!full(&out), "off by default"); + for on in [true, false] { + s.edit_prefs(|p| p.file_handling.pcraft_full_composite = on); + let out = join(&dir, &format!("{on}.pcraft")); + s.execute("file.saveACopy", json!({"path": out})).unwrap(); + assert_eq!(full(&out), on, "preference {on}"); + let out = join(&dir, &format!("{on} param.pcraft")); + s.execute("file.saveACopy", json!({"path": out, "pcraftFullComposite": !on})).unwrap(); + assert_eq!(full(&out), !on, "preference {on}, param {}", !on); + } +} + #[test] fn open_as_forces_the_decoder() { let dir = tmp("openas"); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 38401ff468a..c73e4d77382 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -492,6 +492,9 @@ pub struct FileHandling { pub exr_aces_cg: bool, pub ask_before_saving_layered_tiff: bool, pub maximize_psd_compatibility: Ask, + /// A `.pcraft` save also writes the flattened document at its canvas size as + /// `composite/full.png`. Off by default. + pub pcraft_full_composite: bool, /// SVG groups deeper than this are rasterised on import; parser and document safety caps remain fixed. pub rasterize_svg_groups_deeper_than: u32, pub recent_file_count: u32, @@ -524,6 +527,7 @@ impl Default for FileHandling { exr_aces_cg: false, ask_before_saving_layered_tiff: true, maximize_psd_compatibility: Ask::Always, + pcraft_full_composite: false, rasterize_svg_groups_deeper_than: photocraft_doc::MAX_GROUP_DEPTH as u32, recent_file_count: 20, recent_files: Vec::new(), diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 992e925ae9f..20bd4d95ae0 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -8,6 +8,7 @@ //! blobs/.zst content-addressed binary data (ICC, EXIF, PSD blocks, smart objects) //! thumb.png optional thumbnail (caller-rendered) //! composite/preview.png optional flattened preview (caller-rendered) +//! composite/full.png optional flattened composite at the canvas size (caller-rendered) //! save.lock directory bundles only: held while a save runs (empty) //! ``` //! @@ -84,6 +85,11 @@ pub type Result = std::result::Result; pub struct SaveOptions { pub thumbnail: Option, pub composite: Option, + /// The flattened document at its canvas size, for other apps that read `.pcraft` files. A ZIP + /// save leaves it out when it would take the archive past 4 GiB or 65,535 entries. + pub full_composite: Option, + /// The ICC profile of `full_composite`'s pixels, embedded in its PNG. + pub full_composite_icc: Option>, } /// Limits applied while loading untrusted bundles. diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 0b1e08b7062..84ba3ac99bc 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -31,6 +31,9 @@ pub struct Manifest { pub thumbnail: Option, #[serde(default)] pub composite: Option, + /// The flattened document at its canvas size (absent in older files and in saves without it). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub full_composite: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 97e285a5730..20e8f335518 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -18,6 +18,10 @@ use crate::{FormatError, LoadOptions, Result, SaveOptions}; pub(crate) const MANIFEST: &str = "manifest.json"; pub(crate) const THUMB: &str = "thumb.png"; pub(crate) const COMPOSITE: &str = "composite/preview.png"; +pub(crate) const FULL_COMPOSITE: &str = "composite/full.png"; +/// Bytes a ZIP bundle may hold before its central directory, and entries it may hold: the +/// format's 32-bit offsets and 16-bit counts ([`ZipWriter`] has no ZIP64). +const ZIP_LIMIT: (u64, usize) = (u32::MAX as u64, u16::MAX as usize); /// The file a directory save holds an exclusive lock on for its whole transaction (#4957). pub(crate) const SAVE_LOCK: &str = "save.lock"; /// How long a directory save waits for another save of the same bundle to finish. @@ -59,16 +63,28 @@ fn hash_bytes(b: &[u8]) -> Hash { } fn png(img: &Rgba8Image) -> Result> { + png_tagged(img, None) +} + +/// [`png`] with `icc` embedded. +fn png_tagged(img: &Rgba8Image, icc: Option<&[u8]>) -> Result> { let image = photocraft_codecs::Image::from_u8(img.width, img.height, photocraft_codecs::ChannelLayout::Rgba, img.pixels.clone()) - .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))?; + .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))? + .with_icc(icc.map(<[u8]>::to_vec)); photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).map_err(|e| FormatError::Unsupported(format!("preview: {e}"))) } fn previews(opts: &SaveOptions) -> Result)>> { - let (composite, thumbnail) = beside( - opts.thumbnail.is_some() && opts.composite.is_some(), - || opts.composite.as_ref().map(png).transpose(), - || opts.thumbnail.as_ref().map(png).transpose(), + let (full, (composite, thumbnail)) = beside( + opts.full_composite.is_some() && (opts.thumbnail.is_some() || opts.composite.is_some()), + || opts.full_composite.as_ref().map(|img| png_tagged(img, opts.full_composite_icc.as_deref())).transpose(), + || { + beside( + opts.thumbnail.is_some() && opts.composite.is_some(), + || opts.composite.as_ref().map(png).transpose(), + || opts.thumbnail.as_ref().map(png).transpose(), + ) + }, ); let mut out = Vec::new(); if let Some(t) = thumbnail? { @@ -77,6 +93,9 @@ fn previews(opts: &SaveOptions) -> Result)>> { if let Some(t) = composite? { out.push((COMPOSITE, t)); } + if let Some(t) = full? { + out.push((FULL_COMPOSITE, t)); + } Ok(out) } @@ -160,6 +179,19 @@ const MAX_MANIFEST_DEPTH: usize = 3 * (convert::MAX_GROUP_DEPTH + 1) + 64; /// item, so this still admits manifests of about 80 MiB. const MAX_MANIFEST_ITEMS: usize = 4 << 20; +/// The manifest as a save writes it. +fn manifest_json(manifest: &Manifest) -> Result> { + // serde_json writes NaN and the infinities as `null`, which the manifest's float fields + // refuse on load (issue #1101): refuse the save instead, naming the value. + crate::finite::check(manifest).map_err(|e| match e { + crate::finite::Problem::NonFinite { path } => FormatError::NonFinite { path }, + crate::finite::Problem::Other(m) => FormatError::Unsupported(format!("manifest: {m}")), + })?; + let json = serde_json::to_vec_pretty(manifest)?; + check_manifest_depth(&json)?; + Ok(json) +} + /// Rejects JSON nested deeper than [`MAX_MANIFEST_DEPTH`] or holding more than /// [`MAX_MANIFEST_ITEMS`] items with a linear scan (no recursion), so parsing with serde_json's /// recursion limit disabled can't exhaust the stack, nor tiny values the memory, on hostile input. @@ -508,6 +540,8 @@ struct FileSignature { struct Prepared { manifest: Vec, + /// What `manifest` encodes, for a ZIP save that has to leave the full-size composite out. + model: Manifest, objects: BTreeMap, stats: SaveStats, } @@ -785,6 +819,7 @@ impl BundleGc { let (handle, name) = match relative { THUMB => (&self.root, THUMB), COMPOSITE => (&self.composite, "preview.png"), + FULL_COMPOSITE => (&self.composite, "full.png"), _ => match relative.split_once('/') { Some(("tiles", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.tiles, name), Some(("blobs", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.blobs, name), @@ -915,15 +950,10 @@ impl PcraftWriter { document, thumbnail: opts.thumbnail.as_ref().map(|_| THUMB.to_owned()), composite: opts.composite.as_ref().map(|_| COMPOSITE.to_owned()), + full_composite: opts.full_composite.as_ref().map(|_| FULL_COMPOSITE.to_owned()), }; - // serde_json writes NaN and the infinities as `null`, which the manifest's float fields - // refuse on load (issue #1101): refuse the save instead, naming the value. - crate::finite::check(&manifest).map_err(|e| match e { - crate::finite::Problem::NonFinite { path } => FormatError::NonFinite { path }, - crate::finite::Problem::Other(m) => FormatError::Unsupported(format!("manifest: {m}")), - })?; - let manifest = serde_json::to_vec_pretty(&manifest)?; - check_manifest_depth(&manifest)?; + let model = manifest; + let manifest = manifest_json(&model)?; let stats = SaveStats { tiles_total: c.tiles.len(), blobs_total: c.blobs.len(), manifest_bytes: manifest.len(), ..Default::default() }; let mut objects = BTreeMap::new(); for (h, (t, s)) in c.tiles { @@ -932,15 +962,21 @@ impl PcraftWriter { for (h, b) in c.blobs { objects.insert(blob_path(&h), Object::Blob(b)); } - Ok(Prepared { manifest, objects, stats }) + Ok(Prepared { manifest, model, objects, stats }) } /// Save as a ZIP bundle in memory. pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec, SaveStats)> { + self.save_zip_within(doc, opts, ZIP_LIMIT) + } + + /// [`Self::save_zip`] with `limit` (bytes, entries) in place of [`ZIP_LIMIT`]: an archive that + /// the full-size composite would take past either is saved without that composite. + fn save_zip_within(&mut self, doc: &Document, opts: &SaveOptions, limit: (u64, usize)) -> Result<(Vec, SaveStats)> { // Another thread encodes the previews while the document is collected and its new // objects are compressed on all cores (zstd dominates a full save). let (previews, prepared) = beside( - opts.thumbnail.is_some() || opts.composite.is_some(), + opts.thumbnail.is_some() || opts.composite.is_some() || opts.full_composite.is_some(), || previews(opts), || -> Result<_> { let p = self.prepare(doc, opts)?; @@ -950,22 +986,9 @@ impl PcraftWriter { }, ); let (p, mut fresh) = prepared?; - let previews = previews?; + let mut previews = previews?; let mut stats = p.stats; - let mut next = HashMap::with_capacity(p.objects.len()); - let mut cached_bytes = 0usize; - // The archive is sized for every entry up front (#7689): previews, then reused and fresh - // objects at their compressed sizes. - let entries = - std::iter::once((MANIFEST, p.manifest.len())).chain(previews.iter().map(|(name, data)| (*name, data.len()))).chain(p.objects.keys().map(|path| { - let size = self.compressed.get(path).or_else(|| fresh.get(path)).map_or(0, |data| data.len()); - (path.as_str(), size) - })); - let mut z = ZipWriter::with_entries(entries)?; - z.add(MANIFEST, &p.manifest)?; - for (name, data) in &previews { - z.add(name, data)?; - } + let mut entries = Vec::with_capacity(p.objects.len()); for (path, obj) in &p.objects { let (key, data) = match self.compressed.remove_entry(path) { Some((key, data)) => { @@ -982,6 +1005,37 @@ impl PcraftWriter { (None, fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed()))) } }; + entries.push((path, key, data)); + } + // A STORE entry takes a 30-byte local header plus its name and data before the central + // directory. The full-size composite is left out rather than fail a save that fits without it. + let stored = |name: &str, len: usize| 30 + name.len() as u64 + len as u64; + let total = stored(MANIFEST, p.manifest.len()) + + previews.iter().map(|(name, data)| stored(name, data.len())).sum::() + + entries.iter().map(|(path, _, data)| stored(path, data.len())).sum::(); + let mut manifest = p.manifest; + if (total > limit.0 || 1 + previews.len() + entries.len() > limit.1) + && let Some(at) = previews.iter().position(|(name, _)| *name == FULL_COMPOSITE) + { + previews.remove(at); + let mut model = p.model; + model.full_composite = None; + manifest = manifest_json(&model)?; + stats.manifest_bytes = manifest.len(); + } + // The archive is sized for every entry up front (#7689): previews, then reused and fresh + // objects at their compressed sizes. + let sizes = std::iter::once((MANIFEST, manifest.len())) + .chain(previews.iter().map(|(name, data)| (*name, data.len()))) + .chain(entries.iter().map(|(path, _, data)| (path.as_str(), data.len()))); + let mut z = ZipWriter::with_entries(sizes)?; + z.add(MANIFEST, &manifest)?; + for (name, data) in &previews { + z.add(name, data)?; + } + let mut next = HashMap::with_capacity(entries.len()); + let mut cached_bytes = 0usize; + for (path, key, data) in entries { z.add(path, &data)?; if data.capacity() <= self.compressed_budget.saturating_sub(cached_bytes) { cached_bytes += data.capacity(); @@ -1009,7 +1063,7 @@ impl PcraftWriter { let existing = list_objects(dir)?; // Reject a hostile existing entry before writing any object or manifest. This also // covers entries that this save would otherwise leave untouched or garbage-collect. - for path in [MANIFEST, THUMB, COMPOSITE] { + for path in [MANIFEST, THUMB, COMPOSITE, FULL_COMPOSITE] { validate_bundle_file(dir, &dir.join(path))?; } let p = self.prepare(doc, opts)?; @@ -1099,7 +1153,7 @@ impl PcraftWriter { write_bundle_file(dir, &dir.join(MANIFEST), &p.manifest, fs)?; // Omitted previews belong to the previous manifest until the new one commits. // After commit, a locked leftover is only housekeeping, just like unused objects. - for stale in [THUMB, COMPOSITE] { + for stale in [THUMB, COMPOSITE, FULL_COMPOSITE] { if !previews.iter().any(|(n, _)| *n == stale) { let _ = remove_bundle_file(dir, &dir.join(stale), &gc); } @@ -1246,35 +1300,90 @@ fn previews_follow_the_manifest_with_the_bytes_of_a_serial_encode() { i.pixels.iter_mut().enumerate().for_each(|(j, p)| *p = (j as u8).wrapping_mul(k)); i }; - let (thumb, composite) = (image(4, 3, 7), image(9, 5, 13)); - for (t, c) in [(true, true), (true, false), (false, true), (false, false)] { - let opts = SaveOptions { thumbnail: t.then(|| thumb.clone()), composite: c.then(|| composite.clone()) }; + let (thumb, composite, full) = (image(4, 3, 7), image(9, 5, 13), image(600, 3, 5)); + for mask in 0..8u8 { + let (t, c, f) = (mask & 1 != 0, mask & 2 != 0, mask & 4 != 0); + let opts = SaveOptions { + thumbnail: t.then(|| thumb.clone()), + composite: c.then(|| composite.clone()), + full_composite: f.then(|| full.clone()), + ..Default::default() + }; let (bytes, _) = PcraftWriter::new().save_zip(&doc, &opts).unwrap(); let zip = ZipReader::new(&bytes).unwrap(); let names: Vec<&str> = zip.entries.iter().map(|e| e.name.as_str()).collect(); let mut want = vec![MANIFEST]; want.extend(t.then_some(THUMB)); want.extend(c.then_some(COMPOSITE)); + want.extend(f.then_some(FULL_COMPOSITE)); assert_eq!(names[..want.len()], want[..]); assert!(names[want.len()..].iter().all(|n| n.starts_with("tiles/") || n.starts_with("blobs/")), "{names:?}"); - for (name, img) in [(THUMB, opts.thumbnail.as_ref()), (COMPOSITE, opts.composite.as_ref())] { + for (name, img) in [(THUMB, opts.thumbnail.as_ref()), (COMPOSITE, opts.composite.as_ref()), (FULL_COMPOSITE, opts.full_composite.as_ref())] { assert_eq!(zip.read_by_name(name, usize::MAX).ok(), img.map(|i| png(i).unwrap()), "{name}"); } + assert_eq!(crate::read_manifest(&bytes).unwrap().full_composite.as_deref(), f.then_some(FULL_COMPOSITE)); } - let bad = SaveOptions { thumbnail: Some(Rgba8Image { width: 4, height: 3, pixels: vec![0; 5] }), composite: Some(composite.clone()) }; + let bad = SaveOptions { thumbnail: Some(Rgba8Image { width: 4, height: 3, pixels: vec![0; 5] }), composite: Some(composite.clone()), ..Default::default() }; assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); - let bad = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(Rgba8Image { width: 9, height: 5, pixels: vec![0; 5] }) }; + let bad = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(Rgba8Image { width: 9, height: 5, pixels: vec![0; 5] }), ..Default::default() }; + assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); + let bad = SaveOptions { full_composite: Some(Rgba8Image { width: 600, height: 3, pixels: vec![0; 5] }), ..Default::default() }; assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); let dir = std::env::temp_dir().join(format!("pcraft-previews-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); - let opts = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(composite.clone()) }; + let opts = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(composite.clone()), full_composite: Some(full.clone()), ..Default::default() }; PcraftWriter::new().save_dir(&doc, &dir, &opts).unwrap(); assert_eq!(std::fs::read(dir.join(THUMB)).unwrap(), png(&thumb).unwrap()); assert_eq!(std::fs::read(dir.join(COMPOSITE)).unwrap(), png(&composite).unwrap()); + assert_eq!(std::fs::read(dir.join(FULL_COMPOSITE)).unwrap(), png(&full).unwrap()); + // A later save without it removes the file once the new manifest is in place. + PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions { full_composite: None, ..opts }).unwrap(); + assert!(!dir.join(FULL_COMPOSITE).exists()); + assert!(dir.join(COMPOSITE).exists()); std::fs::remove_dir_all(&dir).unwrap(); } +#[cfg(test)] +#[test] +fn zip_save_leaves_the_full_composite_out_past_the_zip_limit() { + use photocraft_doc::{Layer, LayerContent}; + use photocraft_geom::Size; + use photocraft_raster::Surface; + + let mut doc = Document::new("limit", Size::new(300, 200), photocraft_color::ColorMode::Rgb, SampleType::U8); + let mut surface = Surface::new(doc.pixel_format()); + surface.write_pixel(7, 9, &[0.2, 0.4, 0.6, 1.0]); + doc.layers.push(Layer::new("pixels", LayerContent::Raster(surface))); + let mut full = Rgba8Image::new(300, 200); + full.pixels.iter_mut().enumerate().for_each(|(i, p)| *p = (i % 251) as u8); + let opts = SaveOptions { + thumbnail: Some(Rgba8Image::new(4, 3)), + composite: Some(Rgba8Image::new(9, 6)), + full_composite: Some(full.clone()), + ..Default::default() + }; + let (whole, _) = PcraftWriter::new().save_zip(&doc, &opts).unwrap(); + // The archive's entries without the central directory, and how many there are: what the + // limit compares. + let archive = ZipReader::new(&whole).unwrap(); + let bytes = archive.entries.iter().map(|e| 30 + e.name.len() as u64 + archive.read(e, usize::MAX).unwrap().len() as u64).sum::(); + let count = archive.entries.len(); + let (fits, _) = PcraftWriter::new().save_zip_within(&doc, &opts, (bytes, count)).unwrap(); + assert_eq!(fits, whole, "an archive at the limit keeps the composite"); + for limit in [(bytes - 1, count), (bytes, count - 1)] { + let (saved, stats) = PcraftWriter::new().save_zip_within(&doc, &opts, limit).unwrap(); + let zip = ZipReader::new(&saved).unwrap(); + let names: Vec<&str> = zip.entries.iter().map(|e| e.name.as_str()).collect(); + assert!(!names.contains(&FULL_COMPOSITE), "{limit:?}: {names:?}"); + assert!(names.contains(&THUMB) && names.contains(&COMPOSITE), "{limit:?}: {names:?}"); + let manifest = zip.read_by_name(MANIFEST, usize::MAX).unwrap(); + assert_eq!(stats.manifest_bytes, manifest.len()); + assert!(!String::from_utf8(manifest).unwrap().contains("full_composite")); + assert_eq!(crate::load_from_bytes(&saved).unwrap(), doc); + } +} + #[cfg(all(test, unix))] #[test] fn gc_pinned_directory_handles_resist_subdirectory_swap() { diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 32ef5031393..02e8b1e8e87 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -490,7 +490,7 @@ fn previews_embedded_and_readable() { let doc = rich_doc(ColorMode::Rgb, SampleType::U8); let mut thumb = Rgba8Image::new(4, 3); thumb.pixels.iter_mut().enumerate().for_each(|(i, p)| *p = i as u8); - let opts = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(thumb.clone()) }; + let opts = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(thumb.clone()), ..Default::default() }; let bytes = save_to_bytes(&doc, &opts).unwrap(); let png = read_thumbnail(&bytes).unwrap().unwrap(); let img = photocraft_codecs::decode(&png).unwrap(); @@ -502,6 +502,36 @@ fn previews_embedded_and_readable() { assert!(read_thumbnail(&save_to_bytes(&doc, &SaveOptions::default()).unwrap()).unwrap().is_none()); } +/// The full-size composite is an optional manifest member: a bundle without it (every file saved +/// before it was written) opens as before, at the same format version. +#[test] +fn bundles_without_the_full_composite_still_open() { + let doc = rich_doc(ColorMode::Rgb, SampleType::U8); + let full = Rgba8Image::new(doc.size.width, doc.size.height); + let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)), full_composite: Some(full), ..Default::default() }; + let bytes = save_to_bytes(&doc, &opts).unwrap(); + let m = read_manifest(&bytes).unwrap(); + assert_eq!(m.full_composite.as_deref(), Some("composite/full.png")); + assert_eq!(m.format_version, 1); + // Rewrite the bundle as an older writer left it: no member in the manifest, no entry. + let r = zip::ZipReader::new(&bytes).unwrap(); + let mut manifest: serde_json::Value = serde_json::from_slice(&r.read_by_name("manifest.json", usize::MAX).unwrap()).unwrap(); + assert!(manifest.as_object_mut().unwrap().remove("full_composite").is_some()); + let mut z = zip::ZipWriter::new(); + z.add("manifest.json", &serde_json::to_vec_pretty(&manifest).unwrap()).unwrap(); + for e in r.entries.iter().filter(|e| e.name != "manifest.json" && e.name != "composite/full.png") { + z.add(&e.name, &r.read(e, usize::MAX).unwrap()).unwrap(); + } + let older = z.finish().unwrap(); + assert_eq!(read_manifest(&older).unwrap().full_composite, None); + assert_eq!(load_from_bytes(&older).unwrap(), load_from_bytes(&bytes).unwrap()); + assert_eq!(load_from_bytes(&older).unwrap(), doc); + // A save without it writes no member at all, as older writers did. + let plain = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + let text = zip::ZipReader::new(&plain).unwrap().read_by_name("manifest.json", usize::MAX).unwrap(); + assert!(!String::from_utf8(text).unwrap().contains("full_composite")); +} + #[test] fn manifest_is_human_readable_json() { let doc = rich_doc(ColorMode::Rgb, SampleType::U8); @@ -911,7 +941,7 @@ fn directory_save_without_previews_removes_stale_files_after_commit() { let mut doc = Document::new("before", photocraft_doc::Size::new(4, 3), ColorMode::Rgb, SampleType::U8); let dir = temp_dir("preview-cleanup"); let mut writer = PcraftWriter::new(); - let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)) }; + let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)), ..Default::default() }; writer.save_dir(&doc, &dir, &opts).unwrap(); doc.name = "after".into(); writer.save_dir(&doc, &dir, &SaveOptions::default()).unwrap(); @@ -931,7 +961,7 @@ fn failed_manifest_commit_preserves_omitted_previews() { let mut doc = Document::with_background("before", photocraft_doc::Size::new(4, 3), ColorMode::Rgb, depth, photocraft_color::Color::WHITE); let dir = temp_dir("locked-manifest-previews"); let mut writer = PcraftWriter::new(); - let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)) }; + let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)), ..Default::default() }; writer.save_dir(&doc, &dir, &opts).unwrap(); let old_doc = doc.clone(); let paths = ["manifest.json", "thumb.png", "composite/preview.png"]; @@ -962,7 +992,7 @@ fn locked_stale_preview_does_not_fail_committed_save() { let mut doc = Document::new("before", photocraft_doc::Size::new(4, 3), ColorMode::Rgb, SampleType::U8); let dir = temp_dir("locked-stale-preview"); let mut writer = PcraftWriter::new(); - let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)) }; + let opts = SaveOptions { thumbnail: Some(Rgba8Image::new(2, 2)), composite: Some(Rgba8Image::new(4, 3)), ..Default::default() }; writer.save_dir(&doc, &dir, &opts).unwrap(); let held = std::fs::OpenOptions::new().read(true).share_mode(3).open(dir.join("thumb.png")).unwrap(); doc.name = "after".into(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 612cd6dd3b7..a5bd0c0956b 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -240,6 +240,9 @@ pub struct ExportOptions { /// PSD/PSB and layered TIFF: read and embed the files linked smart objects name (see /// [`PsdExportOptions::read_linked_files`]). On by default; automation turns it off. pub read_linked_files: bool, + /// `.pcraft`: also write the flattened document at its canvas size as `composite/full.png` + /// (Preferences › File Handling › Save Full-Size Composite in .pcraft Files). Off by default. + pub pcraft_full_composite: bool, } impl Default for ExportOptions { @@ -255,6 +258,7 @@ impl Default for ExportOptions { document_path: None, pcraft_cache: None, read_linked_files: true, + pcraft_full_composite: false, } } } @@ -564,9 +568,11 @@ pub(crate) fn with_span(ctl: &photocraft_raster::Interrupt, lo: f32, hi: f32, } /// Where a .pcraft save's progress stands once its thumbnail, then its 1024 px composite preview, -/// are rendered (the bundle itself is written after them). +/// then its full-size composite when [`ExportOptions::pcraft_full_composite`] asks for one, are +/// rendered (the bundle itself is written after them). const PCRAFT_THUMBNAIL_DONE: f32 = 0.15; const PCRAFT_PREVIEWS_DONE: f32 = 0.4; +const PCRAFT_FULL_COMPOSITE_DONE: f32 = 0.6; /// The share of a PSD/PSB export spent converting the document (layers, then the composite) /// before its bytes are assembled: about 2.7 s of 3.0 s for a 24 MP, 5-layer RGB/8 document. const PSD_MODEL_DONE: f32 = 0.9; @@ -601,7 +607,14 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & let composite = Some(photocraft_compose::thumbnail(doc.as_ref(), 1024)); ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(PCRAFT_PREVIEWS_DONE); - let previews = photocraft_format::SaveOptions { thumbnail, composite }; + let mut full_composite = None; + if opts.pcraft_full_composite { + full_composite = with_span(ctl, PCRAFT_PREVIEWS_DONE, PCRAFT_FULL_COMPOSITE_DONE, |ctl| pcraft_full_composite_with(doc.as_ref(), ctl))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(PCRAFT_FULL_COMPOSITE_DONE); + } + let full_composite_icc = full_composite.as_ref().map(|_| pcraft_full_composite_icc(doc.as_ref())); + let previews = photocraft_format::SaveOptions { thumbnail, composite, full_composite, full_composite_icc }; let bytes = match &opts.pcraft_cache { Some(cache) => cache.encode(doc.as_ref(), &previews)?, None => photocraft_format::save_to_bytes(doc.as_ref(), &previews)?, @@ -645,6 +658,56 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & flat::export_flat_with(doc, format, opts, ctl) } +/// The flattened document at its canvas size, in 8-bit RGBA like a `.pcraft` file's two previews, +/// for the bundle's `composite/full.png`. `None` for a canvas past +/// [`photocraft_compose::MAX_RENDER_PIXELS`], or when its pixels cannot be allocated (a 32-bit +/// target holds less than 2 GiB in one buffer). +pub fn pcraft_full_composite(doc: &Document) -> Option { + pcraft_full_composite_with(doc, &photocraft_raster::Interrupt::NONE).ok().flatten() +} + +/// The ICC profile of [`pcraft_full_composite`]'s pixels: an RGB document's own profile as stored, +/// a gray document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable +/// profile ([`psd_thumbnail::composite_profile`]). +pub fn pcraft_full_composite_icc(doc: &Document) -> Vec { + let own = doc.icc_profile.as_ref().filter(|bytes| { + doc.mode == photocraft_color::ColorMode::Rgb && photocraft_cms::Profile::parse(bytes).is_ok_and(|p| p.color_space == photocraft_cms::ColorSpace::Rgb) + }); + match own { + Some(bytes) => bytes.to_vec(), + None => psd_thumbnail::composite_profile(doc).to_bytes().to_vec(), + } +} + +/// [`pcraft_full_composite`] rendered in bands: `ctl` gets the fraction of rows done, and a +/// cancelled render fails with [`IoError::Cancelled`]. +fn pcraft_full_composite_with(doc: &Document, ctl: &photocraft_raster::Interrupt) -> Result, IoError> { + let canvas = doc.bounds(); + if canvas.is_empty() || u64::from(canvas.width()) * u64::from(canvas.height()) > photocraft_compose::MAX_RENDER_PIXELS { + return Ok(None); + } + let Ok(len) = usize::try_from(u64::from(canvas.width()) * u64::from(canvas.height()) * 4) else { return Ok(None) }; + let mut pixels = Vec::new(); + if pixels.try_reserve_exact(len).is_err() { + return Ok(None); + } + pixels.resize(len, 0); + let mut image = photocraft_raster::Rgba8Image { width: canvas.width(), height: canvas.height(), pixels }; + let row = canvas.width() as usize * 4; + let rows = canvas.height() as f32; + photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; + let start = (band.rect.y0 - canvas.y0) as usize * row; + let pixels = band.to_rgba8().pixels; + if let Some(dst) = image.pixels.get_mut(start..start + pixels.len()) { + dst.copy_from_slice(&pixels); + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + })?; + Ok(Some(image)) +} + /// The PSD's merged composite as straight RGBA floats (row-major), converted /// with the document pixel model and un-matted from white (Photoshop mattes /// the merged image of transparent documents). Used as the compositing oracle. diff --git a/crates/io/src/psd_thumbnail.rs b/crates/io/src/psd_thumbnail.rs index beaccc5bda7..f2165dbb87b 100644 --- a/crates/io/src/psd_thumbnail.rs +++ b/crates/io/src/psd_thumbnail.rs @@ -73,7 +73,7 @@ fn thumbnail_bytes(w: u32, h: u32, jfif: &[u8]) -> Result, IoError> { /// The profile of the compositor's RGB output for `doc`: an RGB document's own (embedded when it /// parses, else sRGB), a gray document's gray profile seen as RGB, and sRGB for CMYK and Lab /// (which the compositor renders in sRGB). -fn composite_profile(doc: &Document) -> Profile { +pub(crate) fn composite_profile(doc: &Document) -> Profile { let space = match doc.mode { ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => ColorSpace::Gray, ColorMode::Cmyk | ColorMode::Lab => return Builtin::Srgb.profile().clone(), diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 40154335d0c..028baf09c3c 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -40,6 +40,7 @@ mod modes; mod multichannel; mod orientation; mod pattern_fill_psd; +mod pcraft_full_composite; mod pcraft_manifest_name; mod pdn_corpus; mod png_text_metadata; diff --git a/crates/io/tests/it/pcraft_full_composite.rs b/crates/io/tests/it/pcraft_full_composite.rs new file mode 100644 index 00000000000..f0710f7878b --- /dev/null +++ b/crates/io/tests/it/pcraft_full_composite.rs @@ -0,0 +1,131 @@ +//! With [`ExportOptions::pcraft_full_composite`] on, a `.pcraft` save writes the flattened +//! document at its canvas size as `composite/full.png`, next to the 256 px thumbnail and the +//! 1024 px preview, so other apps can read the whole image without decoding tiles. Off (the +//! default), the save writes the bundle it wrote before the option existed. + +use photocraft_color::{BlendMode, ColorMode, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent}; +use photocraft_format::zip::ZipReader; +use photocraft_geom::{Rect, Size}; +use photocraft_io::{ExportOptions, export}; +use photocraft_raster::Surface; + +/// A background, a soft Multiply layer at 60 % and a layer that leaves part of the canvas clear. +fn doc(w: u32, h: u32, depth: SampleType) -> Document { + let mut d = Document::new("full", Size::new(w, h), ColorMode::Rgb, depth); + let fmt = d.pixel_format(); + let layer = |name: &str, seed: usize, r: Rect| { + let n = r.width() as usize * r.height() as usize * fmt.bytes_per_pixel(); + let px: Vec = (0..n).map(|i| ((i * 31 + seed * 17 + i / 7) % 251) as u8).collect(); + Layer::new(name, LayerContent::Raster(Surface::from_interleaved(fmt, r, &px))) + }; + d.layers.push(layer("Back", 1, Rect::new(0, 0, w as i32, h as i32 / 2))); + let mut soft = layer("Soft", 2, Rect::new(w as i32 / 4, h as i32 / 4, w as i32, h as i32)); + soft.opacity = 0.6; + soft.blend = BlendMode::Multiply; + d.layers.push(soft); + d +} + +fn on() -> ExportOptions { + ExportOptions { pcraft_full_composite: true, ..Default::default() } +} + +/// The bundle's member named by the manifest's `full_composite`, decoded: size and RGBA8 pixels. +fn full_composite(bytes: &[u8]) -> ((u32, u32), Vec) { + let manifest = photocraft_format::read_manifest(bytes).expect("manifest"); + let path = manifest.full_composite.expect("the manifest names the full-size composite"); + assert_eq!(path, "composite/full.png"); + let png = ZipReader::new(bytes).expect("zip").read_by_name(&path, usize::MAX).expect("entry"); + let image = photocraft_codecs::decode(&png).expect("png"); + (image.dimensions(), image.to_rgba8()) +} + +fn flattened(doc: &Document) -> Vec { + photocraft_compose::render(doc, doc.bounds()).to_rgba8().pixels +} + +#[test] +fn a_default_save_writes_the_bundle_without_the_full_composite() { + for depth in SampleType::ALL { + let d = doc(1500, 700, depth); + let bytes = export(&d, "a.pcraft", &ExportOptions::default()).expect("export").bytes; + assert_eq!(photocraft_format::read_manifest(&bytes).expect("manifest").full_composite, None, "{depth:?}"); + assert!(ZipReader::new(&bytes).expect("zip").find("composite/full.png").is_none(), "{depth:?}"); + // The bytes a save wrote before the option: the bundle with its two previews alone. + let mut named = d.clone(); + named.name = "a.pcraft".into(); + let previews = photocraft_format::SaveOptions { + thumbnail: Some(photocraft_compose::thumbnail(&named, 256)), + composite: Some(photocraft_compose::thumbnail(&named, 1024)), + ..Default::default() + }; + assert!(bytes == photocraft_format::save_to_bytes(&named, &previews).expect("save"), "{depth:?}: the default save changed"); + } +} + +#[test] +fn a_pcraft_save_writes_the_flattened_document_at_its_canvas_size() { + for depth in SampleType::ALL { + let d = doc(300, 200, depth); + let bytes = export(&d, "a.pcraft", &on()).expect("export").bytes; + let (size, pixels) = full_composite(&bytes); + assert_eq!(size, (300, 200), "{depth:?}"); + assert!(pixels == flattened(&d), "{depth:?}: the full-size composite differs from the flattened document"); + assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] == 0), "{depth:?}: transparent pixels stay transparent"); + let mut saved = d.clone(); + saved.name = "a.pcraft".into(); + assert_eq!(photocraft_format::load_from_bytes(&bytes).expect("load"), saved, "{depth:?}"); + } +} + +#[test] +fn a_document_larger_than_the_preview_keeps_its_full_size() { + let d = doc(1500, 700, SampleType::U8); + let bytes = export(&d, "a.pcraft", &on()).expect("export").bytes; + let (size, pixels) = full_composite(&bytes); + assert_eq!(size, (1500, 700)); + assert!(pixels == flattened(&d), "the full-size composite differs from the flattened document"); + let preview = ZipReader::new(&bytes).expect("zip").read_by_name("composite/preview.png", usize::MAX).expect("preview"); + assert_eq!(photocraft_codecs::decode(&preview).expect("png").dimensions(), (1024, 478)); +} + +#[test] +fn the_full_composite_carries_the_profile_of_its_pixels() { + use photocraft_cms::{Builtin, ColorSpace, Profile}; + let full_icc = |d: &Document| { + let bytes = export(d, "a.pcraft", &on()).expect("export").bytes; + let png = ZipReader::new(&bytes).expect("zip").read_by_name("composite/full.png", usize::MAX).expect("entry"); + photocraft_codecs::decode(&png).expect("png").icc.expect("an embedded profile") + }; + let srgb = Builtin::Srgb.profile().to_bytes().to_vec(); + let p3 = Builtin::DisplayP3.profile().to_bytes().to_vec(); + let mut d = doc(40, 30, SampleType::U8); + d.icc_profile = Some(std::sync::Arc::new(p3.clone())); + assert_eq!(full_icc(&d), p3, "the composite is in the document's RGB space"); + d.icc_profile = None; + assert_eq!(full_icc(&d), srgb); + // A CMYK document composites to sRGB: its CMYK profile does not describe the PNG. + let mut cmyk = Document::new("cmyk", Size::new(40, 30), ColorMode::Cmyk, SampleType::U8); + cmyk.icc_profile = Some(std::sync::Arc::new(Builtin::CoatedCmyk.profile().to_bytes().to_vec())); + assert_eq!(full_icc(&cmyk), srgb); + // A gray document's composite repeats its gray samples in R, G and B: the PNG carries its + // gray curve as an RGB profile. + let gray = Builtin::SGray.profile().clone(); + let mut g = Document::new("gray", Size::new(40, 30), ColorMode::Grayscale, SampleType::U8); + g.icc_profile = Some(std::sync::Arc::new(gray.to_bytes().to_vec())); + let tagged = Profile::parse(&full_icc(&g)).expect("profile"); + assert_eq!(tagged.color_space, ColorSpace::Rgb); + assert_eq!(tagged.to_bytes(), gray.gray_as_rgb().expect("gray as RGB").to_bytes()); +} + +#[test] +fn a_canvas_past_the_render_limit_is_saved_without_it() { + // 40000 x 30000 px is over the compositor's 2^30-pixel limit; the layers stay small. + let mut d = doc(64, 64, SampleType::U8); + d.size = Size::new(40_000, 30_000); + assert!(photocraft_io::pcraft_full_composite(&d).is_none()); + let bytes = export(&d, "a.pcraft", &on()).expect("export").bytes; + assert_eq!(photocraft_format::read_manifest(&bytes).expect("manifest").full_composite, None); + assert!(ZipReader::new(&bytes).expect("zip").find("composite/full.png").is_none()); +} diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ebd30492de9..c11d887fd9a 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -346,14 +346,20 @@ impl PhotocraftApp { /// What a save writes by default under the preferences: File Handling › Image Previews /// decides whether a PSD/PSB gets its thumbnail, and Maximize PSD and PSB File Compatibility /// whether it gets its real merged image. Ask When Saving has no dialog here yet, so it saves - /// both, as Photoshop's checkboxes start on. A JPEG or WebP is written the way the active + /// both, as Photoshop's checkboxes start on. Save Full-Size Composite in .pcraft Files decides + /// whether a `.pcraft` save also writes `composite/full.png`. A JPEG or WebP is written the way the active /// document's file was (its JPEG quality, a WebP lossy at its quality or lossless), as /// Photoshop's Save and Save As options start there. pub(crate) fn save_settings(&self) -> ExportSettings { let file_handling = &self.session.prefs().file_handling; let previews = file_handling.image_previews != photocraft_engine::prefs::Ask::Never; let maximize = file_handling.maximize_psd_compatibility != photocraft_engine::prefs::Ask::Never; - let mut settings = ExportSettings { image_previews: previews, psd_maximize_compatibility: maximize, ..ExportSettings::default() }; + let mut settings = ExportSettings { + image_previews: previews, + psd_maximize_compatibility: maximize, + pcraft_full_composite: file_handling.pcraft_full_composite, + ..ExportSettings::default() + }; if let Some(st) = self.session.active() { let e = &st.doc.file_encoding; settings.jpeg_quality = e.jpeg_quality.map(|q| q.clamp(1, 100)); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ad024ccd973..34d3ad150ce 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3942,6 +3942,7 @@ navigator Zoom Zvětšení Chisel Soft Měkké tesání Open color-less EXR as ACEScg Otevřít EXR bez údaje o barevném prostoru jako ACEScg Do not append "copy" to filename when saving a copy Nepřidávat „copy“ k názvu souboru při ukládání kopie + Save Full-Size Composite in .pcraft Files Ukládat složený obraz v plné velikosti do souborů .pcraft # View › Guides › right-click a guide Edit Selected Guides Upravit vybraná vodítka diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c1dfc027ed9..4c1264e3422 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3346,6 +3346,7 @@ curves Smooth Glätten Chisel Soft Meißeln weich Open color-less EXR as ACEScg Farbangabenloses EXR als ACEScg öffnen Do not append "copy" to filename when saving a copy Beim Speichern einer Kopie „copy“ nicht an den Dateinamen anhängen + Save Full-Size Composite in .pcraft Files Kompositbild in voller Größe in .pcraft-Dateien speichern # Export As metadata and profile options Color Profile Farbprofil EXIF EXIF diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b2b35dbbdce..f2315a71866 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4028,6 +4028,7 @@ curves Smooth Εξομάλυνση Chisel Soft Μαλακή σμίλευση Open color-less EXR as ACEScg Άνοιγμα EXR χωρίς χρωματική δήλωση ως ACEScg Do not append "copy" to filename when saving a copy Να μην προστίθεται «copy» στο όνομα αρχείου κατά την αποθήκευση αντιγράφου + Save Full-Size Composite in .pcraft Files Αποθήκευση σύνθετης εικόνας πλήρους μεγέθους στα αρχεία .pcraft # Export As metadata and profile options EXIF EXIF diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index b42f3be02cc..1f1c3d860e9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4291,6 +4291,7 @@ navigator Zoom Zoom Chisel Soft Cincelar suave Open color-less EXR as ACEScg Abrir EXR sin espacio de color como ACEScg Do not append "copy" to filename when saving a copy No añadir «copy» al nombre de archivo al guardar una copia + Save Full-Size Composite in .pcraft Files Guardar la imagen compuesta a tamaño completo en los archivos .pcraft # Export As metadata and profile options # View › Guides › right-click a guide diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3bad30d474f..6f5f9f1ee85 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3338,6 +3338,7 @@ curves Smooth Lisser Chisel Soft Ciselage doux Open color-less EXR as ACEScg Ouvrir les EXR sans espace colorimétrique en ACEScg Do not append "copy" to filename when saving a copy Ne pas ajouter « copy » au nom de fichier lors de l’enregistrement d’une copie + Save Full-Size Composite in .pcraft Files Enregistrer l’image composite en taille réelle dans les fichiers .pcraft # View › Guides › right-click a guide Edit Selected Guides Modifier les repères sélectionnés diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d632cb52f16..1c501888a50 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4220,6 +4220,7 @@ cameraRaw Yellow Sárga Chisel Soft Lágy vésés Open color-less EXR as ACEScg Színinformáció nélküli EXR megnyitása ACEScg-ként Do not append "copy" to filename when saving a copy Ne fűzze a „copy” szót a fájlnévhez másolat mentésekor + Save Full-Size Composite in .pcraft Files Teljes méretű kompozit kép mentése a .pcraft fájlokba # View › Guides › right-click a guide Edit Selected Guides Kijelölt segédvonalak szerkesztése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 771e04e80a5..20d0676689e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3341,6 +3341,7 @@ curves Smooth Haluskan Chisel Soft Pahat Lembut Open color-less EXR as ACEScg Buka EXR tanpa informasi warna sebagai ACEScg Do not append "copy" to filename when saving a copy Jangan tambahkan "copy" ke nama file saat menyimpan salinan + Save Full-Size Composite in .pcraft Files Simpan gambar komposit ukuran penuh di file .pcraft # View › Guides › right-click a guide Edit Selected Guides Edit Panduan Terpilih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b1598ac237e..d4c6b98ed9d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4293,6 +4293,7 @@ navigator Zoom Zoom Chisel Soft Cesello morbido Open color-less EXR as ACEScg Apri gli EXR senza spazio colore come ACEScg Do not append "copy" to filename when saving a copy Non aggiungere "copy" al nome del file quando si salva una copia + Save Full-Size Composite in .pcraft Files Salva l'immagine composita a dimensione piena nei file .pcraft # Color management, Liquify, glyph group, warp and Camera Raw labels the Serbian, Vietnamese and Japanese catalogs added Adobe-rgb-compat Adobe RGB (compatibile) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 435813b0c7e..efd5487e99c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4008,6 +4008,7 @@ curves Smooth スムーズ Chisel Soft チゼルソフト Open color-less EXR as ACEScg 色空間のないEXRをACEScgとして開く Do not append "copy" to filename when saving a copy コピーを保存するときにファイル名に「copy」を付けない + Save Full-Size Composite in .pcraft Files .pcraftファイルにフルサイズの合成画像を保存 # View › Guides › right-click a guide Edit Selected Guides 選択したガイドを編集 Clear Selected Guides 選択したガイドを消去 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 30ab8cb165f..c73d457be4e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3533,6 +3533,7 @@ curves Smooth 매끄럽게 Chisel Soft 부드럽게 조각 Open color-less EXR as ACEScg 색 공간 정보 없는 EXR을 ACEScg로 열기 Do not append "copy" to filename when saving a copy 사본 저장 시 파일 이름에 "copy"를 붙이지 않음 + Save Full-Size Composite in .pcraft Files .pcraft 파일에 전체 크기 합성 이미지 저장 # Export As metadata and profile options Color Profile 색상 프로필 EXIF EXIF diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d03260ecaf8..1e01f7e6d8e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4090,6 +4090,7 @@ curves Smooth Vloeiend maken Chisel Soft Beitel zacht Open color-less EXR as ACEScg EXR zonder kleurruimte als ACEScg openen Do not append "copy" to filename when saving a copy Geen "copy" aan de bestandsnaam toevoegen bij het opslaan van een kopie + Save Full-Size Composite in .pcraft Files Samengestelde afbeelding op volle grootte opslaan in .pcraft-bestanden # View › Guides › right-click a guide Edit Selected Guides Geselecteerde hulplijnen bewerken diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ba41a4e34d4..791ff3ff4a5 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3945,6 +3945,7 @@ curves Smooth Wygładź Chisel Soft Dłuto miękkie Open color-less EXR as ACEScg Otwieraj EXR bez profilu koloru jako ACEScg Do not append "copy" to filename when saving a copy Nie dodawaj „copy” do nazwy pliku przy zapisywaniu kopii + Save Full-Size Composite in .pcraft Files Zapisuj obraz złożony w pełnym rozmiarze w plikach .pcraft # View › Guides › right-click a guide Edit Selected Guides Edytuj zaznaczone prowadnice diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f3335cd9c6e..3b53f6d3cd9 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4120,6 +4120,7 @@ layerLabel No Color Sem cor Chisel Soft Cinzel suave Open color-less EXR as ACEScg Abrir EXR sem espaço de cor como ACEScg Do not append "copy" to filename when saving a copy Não acrescentar "copy" ao nome do arquivo ao salvar uma cópia + Save Full-Size Composite in .pcraft Files Salvar a imagem composta em tamanho real nos arquivos .pcraft # View › Guides › right-click a guide Edit Selected Guides Editar guias selecionadas diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b74c3983129..b350b80f2cf 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3304,6 +3304,7 @@ curves Smooth Сгладить Chisel Soft Мягкая огранка Open color-less EXR as ACEScg Открывать EXR без цветового профиля как ACEScg Do not append "copy" to filename when saving a copy Не добавлять «copy» к имени файла при сохранении копии + Save Full-Size Composite in .pcraft Files Сохранять сведённое изображение в полном размере в файлах .pcraft # View › Guides › right-click a guide Edit Selected Guides Изменить выбранные направляющие diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index a81eb06da2d..fb92311de17 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4360,6 +4360,7 @@ shape Appearance Izgled Chisel Soft Meko klesanje Open color-less EXR as ACEScg Otvori EXR bez podatka o bojama kao ACEScg Do not append "copy" to filename when saving a copy Ne dodaji „copy“ u ime fajla pri čuvanju kopije + Save Full-Size Composite in .pcraft Files Čuvaj složenu sliku u punoj veličini u .pcraft fajlovima Show home recent files Prikaži nedavne datoteke na početnom ekranu # View › Guides › right-click a guide diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f5b9d13fd6f..a4978740543 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4032,6 +4032,7 @@ cameraData Lens Lens Chisel Soft Yumuşak Keski Open color-less EXR as ACEScg Renk bilgisi olmayan EXR'yi ACEScg olarak aç Do not append "copy" to filename when saving a copy Kopya kaydederken dosya adına "copy" ekleme + Save Full-Size Composite in .pcraft Files .pcraft dosyalarına tam boyutlu bileşik görüntüyü kaydet # View › Guides › right-click a guide Edit Selected Guides Seçili Kılavuzları Düzenle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8d911b19a83..3ea991da281 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4030,6 +4030,7 @@ curves Smooth Згладити Chisel Soft М'яке різьблення Open color-less EXR as ACEScg Відкривати EXR без колірного профілю як ACEScg Do not append "copy" to filename when saving a copy Не додавати «copy» до імені файлу під час збереження копії + Save Full-Size Composite in .pcraft Files Зберігати зведене зображення в повному розмірі у файлах .pcraft # View › Guides › right-click a guide Edit Selected Guides Редагувати вибрані напрямні diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f3486629750..5091594d411 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3793,6 +3793,7 @@ curves Smooth Làm mượt Chisel Soft Đục mềm Open color-less EXR as ACEScg Mở EXR không khai báo màu sắc dưới dạng ACEScg Do not append "copy" to filename when saving a copy Không thêm "copy" vào tên tệp khi lưu bản sao + Save Full-Size Composite in .pcraft Files Lưu ảnh tổng hợp kích thước đầy đủ trong tệp .pcraft # View › Guides › right-click a guide Edit Selected Guides Sửa đường căn đã chọn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9f437214ad..112ab6f8473 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2981,6 +2981,7 @@ curves Smooth 平滑 Chisel Soft 雕刻柔和 Open color-less EXR as ACEScg 将无色彩空间信息的 EXR 以 ACEScg 打开 Do not append "copy" to filename when saving a copy 存储副本时不在文件名后添加“copy” + Save Full-Size Composite in .pcraft Files 在 .pcraft 文件中存储全尺寸合成图像 # Export As metadata and profile options Color Profile 颜色配置文件 EXIF EXIF diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9d46dcb21e8..d5b9439cd07 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2945,6 +2945,7 @@ curves Smooth 平滑 Chisel Soft 雕刻柔和 Open color-less EXR as ACEScg 將無色彩空間資訊的 EXR 以 ACEScg 開啟 Do not append "copy" to filename when saving a copy 儲存副本時不在檔名後加上「copy」 + Save Full-Size Composite in .pcraft Files 在 .pcraft 檔案中儲存全尺寸合成影像 # Export As metadata and profile options Color Profile 色彩描述檔 EXIF EXIF diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index cd1c8675210..36fe4d66276 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -63,6 +63,9 @@ pub(super) fn humanize(key: &str) -> String { if key == "doNotAppendCopy" { return "Do not append \"copy\" to filename when saving a copy".into(); } + if key == "pcraftFullComposite" { + return "Save Full-Size Composite in .pcraft Files".into(); + } // Plug-ins: Photoshop's wording (#9392). if key == "generatorEnabled" { return "Enable Generator".into(); diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs index 97f252772fb..f23a440d4dc 100644 --- a/crates/ui-egui/src/save_identity_tests.rs +++ b/crates/ui-egui/src/save_identity_tests.rs @@ -248,6 +248,29 @@ fn maximize_compatibility_preference_reaches_the_exporter() { } } +/// Preferences › File Handling › Save Full-Size Composite in .pcraft Files reaches the exporter +/// of Save As, Save and automation saves, and is off by default. +#[test] +fn full_composite_preference_reaches_the_exporter() { + let seen = Rc::new(RefCell::new(Vec::new())); + let mut app = app(); + assert!(!app.save_settings().pcraft_full_composite, "off by default"); + let log = seen.clone(); + app.services.export = Some(Box::new(move |_, _, settings: &ExportSettings| { + log.borrow_mut().push(settings.io_options().pcraft_full_composite); + Ok((b"out".to_vec(), Vec::new())) + })); + let ctx = egui::Context::default(); + for value in [true, false] { + app.run("prefs.set", json!({"path": "fileHandling.pcraftFullComposite", "value": value})).unwrap(); + seen.borrow_mut().clear(); + menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": format!("{value}.pcraft")})).unwrap(); + menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap(); + app.save_automation(Some(format!("{value} agent.pcraft"))).unwrap(); + assert_eq!(*seen.borrow(), [value; 3], "{value}"); + } +} + /// #2399: Save and Save As start at the opened file's own encoding: a JPEG's estimated quality, /// a WebP lossy (at its quality) or lossless; a new document keeps the codec defaults. #[test] diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index d330884a0af..0ad7dd8b6a7 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -89,6 +89,9 @@ pub struct ExportSettings { /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB /// File Compatibility; see [`PhotocraftApp::save_settings`]). pub psd_maximize_compatibility: bool, + /// `.pcraft`: also write the full-size composite (Preferences › File Handling › Save Full-Size + /// Composite in .pcraft Files; see [`PhotocraftApp::save_settings`]). Off by default. + pub pcraft_full_composite: bool, /// Embed the document's ICC profile when the format supports it. On for Save As and, unless /// Export As turns it off, for export. pub embed_icc: bool, @@ -118,6 +121,7 @@ impl Default for ExportSettings { dds: photocraft_io::DdsOptions::default(), image_previews: true, psd_maximize_compatibility: true, + pcraft_full_composite: false, embed_icc: true, embed_metadata: true, document_path: None, @@ -148,6 +152,7 @@ impl ExportSettings { opts.encode.dds = self.dds; opts.image_previews = self.image_previews; opts.psd_maximize_compatibility = self.psd_maximize_compatibility; + opts.pcraft_full_composite = self.pcraft_full_composite; opts.document_path = self.document_path.clone(); opts.pcraft_cache = self.pcraft_cache.clone(); opts.read_linked_files = self.read_linked_files; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cd8f370ce65..750ef5d22bd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -418,7 +418,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/development.md b/docs/development.md index 337dcbaaf09..bf0bd701023 100644 --- a/docs/development.md +++ b/docs/development.md @@ -242,6 +242,7 @@ cargo run -p photocraft-cli --example man-and-completions -- out/ # man pa - `manifest.json`: the versioned document tree, with migrations in `format/src/migrate.rs`. - `tiles/.zst` and `blobs/.zst`: zstd-compressed objects, content-addressed by the BLAKE3 hash of their uncompressed bytes. - `thumb.png` and `composite/preview.png`: previews. +- `composite/full.png`: the flattened document at the canvas size, for other apps that read `.pcraft` files. Saves write it only when asked (`ExportOptions::pcraft_full_composite`, off by default). - `save.lock` (directory bundles only): an empty file a save holds an OS file lock on, so two writers or processes saving one bundle take turns (#4957). Keep one `PcraftWriter` per open document: re-saving then only compresses and writes tiles that changed. Directory bundles verify objects on first encounter in a folder; later saves reuse them while their file size and modification time are unchanged, and re-verify changed objects, repair missing or damaged objects, and garbage-collect unreferenced ones. `format::Autosaver` writes snapshots into a recovery directory on a background thread. `list_recovery` / `recover` / `discard_recovery` implement crash recovery, and `format::RecoveryStore` is the lifecycle the desktop app uses: new documents autosave under per-launch keys (document ids restart every launch, so they never overwrite an older entry), and a recovered document adopts the entry it came from. That entry is replaced in place by the next autosave and removed only when the document is saved or closed, never just because it was recovered, so a second crash loses nothing. The web build has no crash recovery (no autosave services). diff --git a/docs/scorecard.md b/docs/scorecard.md index 70b08b831b7..59f66d1017d 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 181 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 182 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -187,7 +187,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 181** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 182** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From ddd11aaa9a8de13dd6b7727508323c6c20834681 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 27 Oct 2026 22:02:30 -0700 Subject: [PATCH 2/8] Format: a full-size composite that fails is left out, and pcraftFullComposite takes only booleans - The PNG encoder gets a fallibly reserved copy of the composite's pixels instead of a clone, and a full-size composite that cannot be copied or encoded is left out of the ZIP or directory bundle and out of its manifest; the save goes on without it. - The ZIP size limit for keeping the full-size composite counts the central directory and end record as well as the entries. - `pcraftFullComposite` that is not true, false or null is a bad parameter of `file.saveACopy`, the other engine saves and the automation `doc.save`. - MCP `doc_save` in bridge mode refuses `pcraftFullComposite: false` as well as `true`. The app's `app.save` does not take the option. --- book/src/formats/pcraft.md | 2 +- crates/automation/src/rpc.rs | 4 +- crates/automation/src/server.rs | 12 ++-- crates/automation/tests/it/mcp.rs | 2 + .../tests/it/native_full_composite.rs | 5 ++ crates/engine/src/cmd/file_cmds.rs | 4 +- crates/engine/src/cmd/file_cmds/save.rs | 14 ++++- crates/engine/src/cmd/file_cmds/tests.rs | 9 +++ crates/format/src/lib.rs | 3 +- crates/format/src/store.rs | 62 ++++++++++++++----- 10 files changed, 93 insertions(+), 24 deletions(-) diff --git a/book/src/formats/pcraft.md b/book/src/formats/pcraft.md index 46a3dc553ca..43abc198408 100644 --- a/book/src/formats/pcraft.md +++ b/book/src/formats/pcraft.md @@ -14,7 +14,7 @@ save.lock `thumb.png` (at most 256 px on the longer side), `composite/preview.png` (at most 1024 px) and `composite/full.png` (the canvas size) are the flattened document as 8-bit RGBA PNGs, whatever the document's depth. The manifest names each one it holds, under `thumbnail`, `composite` and `full_composite`. -A save writes `composite/full.png` only when it is asked to: *Save Full-Size Composite in .pcraft Files* in Preferences › File Handling for the app's saves, `"pcraftFullComposite": true` for the engine's `file.saveACopy` and its batch and export commands, and for the automation `doc.save` and MCP `doc_save`, and `--pcraft-full-composite` for `photocraft-cli convert`, `run` and `batch`. It is off by default. `composite/full.png` embeds the ICC profile of its pixels: an RGB document's own profile, a grayscale document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable profile. A save leaves it out when the canvas is larger than 2^30 pixels, when its pixels cannot be allocated, or when a ZIP bundle would pass 4 GiB or 65,535 entries with it. A directory bundle saved without it has the file from an earlier save removed. +A save writes `composite/full.png` only when it is asked to: *Save Full-Size Composite in .pcraft Files* in Preferences › File Handling for the app's saves, `"pcraftFullComposite": true` for the engine's `file.saveACopy` and its batch and export commands, and for the automation `doc.save` and MCP `doc_save`, and `--pcraft-full-composite` for `photocraft-cli convert`, `run` and `batch`. It is off by default. `composite/full.png` embeds the ICC profile of its pixels: an RGB document's own profile, a grayscale document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable profile. A save leaves it out when the canvas is larger than 2^30 pixels, when its pixels cannot be allocated or encoded, or when a ZIP bundle would pass 4 GiB or 65,535 entries with it. A directory bundle saved without it has the file from an earlier save removed. `save.lock` exists only in directory bundles: a save holds an OS file lock on it while it writes objects, publishes the manifest and removes unreferenced objects, so concurrent saves of one bundle take turns. It is empty, and readers ignore it. diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index db0807fb247..7fb840c981a 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -126,7 +126,9 @@ impl Headless { let mut opts = photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, - pcraft_full_composite: p.get("pcraftFullComposite").and_then(Value::as_bool).unwrap_or(false), + pcraft_full_composite: photocraft_engine::file_cmds::pcraft_full_composite_param(&p, "doc.save") + .map_err(|e| bad(e.to_string()))? + .unwrap_or(false), ..Default::default() }; opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 11acba25d9c..b33ed713ad4 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -194,7 +194,7 @@ pub struct SaveParams { /// .pcraft: also write the flattened document at its canvas size as `composite/full.png`. /// Off by default. #[serde(default, rename = "pcraftFullComposite")] - pub pcraft_full_composite: bool, + pub pcraft_full_composite: Option, #[serde(default)] pub index: Option, } @@ -1081,7 +1081,7 @@ impl PhotocraftMcp { p.format.is_some().then_some("format"), p.quality.is_some().then_some("quality"), p.tiff_layers.then_some("tiffLayers"), - p.pcraft_full_composite.then_some("pcraftFullComposite"), + p.pcraft_full_composite.is_some().then_some("pcraftFullComposite"), dpx_bits.is_some().then_some("dpxBits"), p.index.is_some().then_some("index"), ] @@ -1108,8 +1108,12 @@ impl PhotocraftMcp { } let Some(r) = self .headless_op(move |h| { - let mut opts = - photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, pcraft_full_composite: p.pcraft_full_composite, ..Default::default() }; + let mut opts = photocraft_io::ExportOptions { + tiff_layers: p.tiff_layers, + tga_bits, + pcraft_full_composite: p.pcraft_full_composite.unwrap_or(false), + ..Default::default() + }; opts.encode.dpx_bits = dpx_bits; opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; if let Some(q) = p.quality { diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index 0ac5c17a5fc..449eb24179b 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -356,6 +356,8 @@ async fn bridge_doc_save_rejects_headless_only_options_instead_of_saving_with_de json!({"path": "out.jpg", "quality": 50}), json!({"path": "out.png", "format": "png"}), json!({"path": "out.tif", "tiffLayers": true}), + json!({"path": "out.pcraft", "pcraftFullComposite": true}), + json!({"path": "out.pcraft", "pcraftFullComposite": false}), json!({"path": "out.pcraft", "index": 0}), ] { let r = call(&client, "doc_save", params.clone()).await; diff --git a/crates/automation/tests/it/native_full_composite.rs b/crates/automation/tests/it/native_full_composite.rs index fea554c19d1..c3cff93874a 100644 --- a/crates/automation/tests/it/native_full_composite.rs +++ b/crates/automation/tests/it/native_full_composite.rs @@ -41,5 +41,10 @@ fn scripted_native_saves_write_the_full_size_composite_when_asked() { assert!(!has_full_composite(&std::fs::read(&path).unwrap()), "off by default"); headless.handle("doc.save", json!({"path": path.to_str().unwrap(), "pcraftFullComposite": true})).unwrap(); assert_eq!(full_composite(&std::fs::read(&path).unwrap()), ((40, 30), flattened)); + for bad in [json!("true"), json!(1)] { + let err = headless.handle("doc.save", json!({"path": dir.join("Bad.pcraft").to_str().unwrap(), "pcraftFullComposite": bad})).unwrap_err(); + assert!(format!("{err:?}").contains("`pcraftFullComposite` must be true or false"), "{bad}: {err:?}"); + assert!(!dir.join("Bad.pcraft").exists(), "{bad}: nothing is written"); + } std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 8291b061ffc..7637f702860 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -50,7 +50,9 @@ pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; -pub use save::{dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, tga_bits_param, tiff_compression_param, tiff_would_write_layers}; +pub use save::{ + dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, pcraft_full_composite_param, tga_bits_param, tiff_compression_param, tiff_would_write_layers, +}; mod batch_naming; diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index c1175624650..89410a6700e 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -75,7 +75,7 @@ impl SaveOpts { dds: dds_param(p, cmd)?.unwrap_or_default(), image_previews: file_handling.image_previews != crate::prefs::Ask::Never, psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, - pcraft_full_composite: p.get("pcraftFullComposite").and_then(Value::as_bool).unwrap_or(file_handling.pcraft_full_composite), + pcraft_full_composite: pcraft_full_composite_param(p, cmd)?.unwrap_or(file_handling.pcraft_full_composite), }) } @@ -105,6 +105,18 @@ pub fn tga_bits_param(p: &Value, cmd: &str) -> Result Result> { + match p.get("pcraftFullComposite") { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_bool() + .map(Some) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("`pcraftFullComposite` must be true or false, got {v}") }), + } +} + /// The TIFF compression in `p` (`"tiffCompression": "none" | "lzw" | "zip"`, Photoshop's TIFF /// Options; absent or null: none). Anything else is a bad parameter of command `cmd` (#5301). pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index eae4793d915..7ff1023b2ac 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -476,6 +476,15 @@ fn full_composite_preference_controls_the_pcraft_full_size_composite() { s.execute("file.saveACopy", json!({"path": out, "pcraftFullComposite": !on})).unwrap(); assert_eq!(full(&out), !on, "preference {on}, param {}", !on); } + let out = join(&dir, "null param.pcraft"); + s.execute("file.saveACopy", json!({"path": out, "pcraftFullComposite": null})).unwrap(); + assert!(!full(&out), "null takes the preference"); + for bad in [json!("true"), json!(1)] { + let out = join(&dir, "bad param.pcraft"); + let err = s.execute("file.saveACopy", json!({"path": out, "pcraftFullComposite": bad})).unwrap_err().to_string(); + assert!(err.contains("`pcraftFullComposite` must be true or false"), "{bad}: {err}"); + assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing is written"); + } } #[test] diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 20bd4d95ae0..6e492cdd82f 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -86,7 +86,8 @@ pub struct SaveOptions { pub thumbnail: Option, pub composite: Option, /// The flattened document at its canvas size, for other apps that read `.pcraft` files. A ZIP - /// save leaves it out when it would take the archive past 4 GiB or 65,535 entries. + /// save leaves it out when it would take the archive past 4 GiB or 65,535 entries, and every + /// save leaves it out when it cannot be encoded. pub full_composite: Option, /// The ICC profile of `full_composite`'s pixels, embedded in its PNG. pub full_composite_icc: Option>, diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 20e8f335518..4c750afd982 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -19,7 +19,7 @@ pub(crate) const MANIFEST: &str = "manifest.json"; pub(crate) const THUMB: &str = "thumb.png"; pub(crate) const COMPOSITE: &str = "composite/preview.png"; pub(crate) const FULL_COMPOSITE: &str = "composite/full.png"; -/// Bytes a ZIP bundle may hold before its central directory, and entries it may hold: the +/// Bytes a ZIP bundle may hold, central directory included, and entries it may hold: the /// format's 32-bit offsets and 16-bit counts ([`ZipWriter`] has no ZIP64). const ZIP_LIMIT: (u64, usize) = (u32::MAX as u64, u16::MAX as usize); /// The file a directory save holds an exclusive lock on for its whole transaction (#4957). @@ -68,7 +68,10 @@ fn png(img: &Rgba8Image) -> Result> { /// [`png`] with `icc` embedded. fn png_tagged(img: &Rgba8Image, icc: Option<&[u8]>) -> Result> { - let image = photocraft_codecs::Image::from_u8(img.width, img.height, photocraft_codecs::ChannelLayout::Rgba, img.pixels.clone()) + let mut pixels = Vec::new(); + pixels.try_reserve_exact(img.pixels.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for preview".into()))?; + pixels.extend_from_slice(&img.pixels); + let image = photocraft_codecs::Image::from_u8(img.width, img.height, photocraft_codecs::ChannelLayout::Rgba, pixels) .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))? .with_icc(icc.map(<[u8]>::to_vec)); photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).map_err(|e| FormatError::Unsupported(format!("preview: {e}"))) @@ -93,7 +96,8 @@ fn previews(opts: &SaveOptions) -> Result)>> { if let Some(t) = composite? { out.push((COMPOSITE, t)); } - if let Some(t) = full? { + // A full-size composite that cannot be encoded is left out; the save goes on without it. + if let Ok(Some(t)) = full { out.push((FULL_COMPOSITE, t)); } Ok(out) @@ -546,6 +550,18 @@ struct Prepared { stats: SaveStats, } +impl Prepared { + /// Takes the full-size composite out of the manifest when `previews` does not hold it. + fn match_previews(&mut self, previews: &[(&str, Vec)]) -> Result<()> { + if self.model.full_composite.is_some() && !previews.iter().any(|(name, _)| *name == FULL_COMPOSITE) { + self.model.full_composite = None; + self.manifest = manifest_json(&self.model)?; + self.stats.manifest_bytes = self.manifest.len(); + } + Ok(()) + } +} + enum Object { Tile(Arc, SampleType), Blob(Arc>), @@ -985,8 +1001,9 @@ impl PcraftWriter { Ok((p, fresh)) }, ); - let (p, mut fresh) = prepared?; + let (mut p, mut fresh) = prepared?; let mut previews = previews?; + p.match_previews(&previews)?; let mut stats = p.stats; let mut entries = Vec::with_capacity(p.objects.len()); for (path, obj) in &p.objects { @@ -1007,10 +1024,12 @@ impl PcraftWriter { }; entries.push((path, key, data)); } - // A STORE entry takes a 30-byte local header plus its name and data before the central - // directory. The full-size composite is left out rather than fail a save that fits without it. - let stored = |name: &str, len: usize| 30 + name.len() as u64 + len as u64; - let total = stored(MANIFEST, p.manifest.len()) + // A STORE entry takes a 30-byte local header plus its name and data, and a 46-byte central + // directory record plus its name again; the archive ends with a 22-byte end record. The + // full-size composite is left out rather than fail a save that fits without it. + let stored = |name: &str, len: usize| 76 + 2 * name.len() as u64 + len as u64; + let total = 22 + + stored(MANIFEST, p.manifest.len()) + previews.iter().map(|(name, data)| stored(name, data.len())).sum::() + entries.iter().map(|(path, _, data)| stored(path, data.len())).sum::(); let mut manifest = p.manifest; @@ -1066,8 +1085,9 @@ impl PcraftWriter { for path in [MANIFEST, THUMB, COMPOSITE, FULL_COMPOSITE] { validate_bundle_file(dir, &dir.join(path))?; } - let p = self.prepare(doc, opts)?; + let mut p = self.prepare(doc, opts)?; let previews = previews(opts)?; + p.match_previews(&previews)?; let mut stats = p.stats; if self.verified_directory.as_ref().is_none_or(|cache| cache.directory != canonical_dir) { self.verified_directory = Some(DirectoryVerificationCache { directory: canonical_dir.clone(), ..Default::default() }); @@ -1327,8 +1347,21 @@ fn previews_follow_the_manifest_with_the_bytes_of_a_serial_encode() { assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); let bad = SaveOptions { thumbnail: Some(thumb.clone()), composite: Some(Rgba8Image { width: 9, height: 5, pixels: vec![0; 5] }), ..Default::default() }; assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); - let bad = SaveOptions { full_composite: Some(Rgba8Image { width: 600, height: 3, pixels: vec![0; 5] }), ..Default::default() }; - assert!(matches!(PcraftWriter::new().save_zip(&doc, &bad), Err(FormatError::Unsupported(m)) if m.starts_with("preview"))); + // A full-size composite that cannot be encoded is left out, and the save goes on without it. + let bad = + SaveOptions { thumbnail: Some(thumb.clone()), full_composite: Some(Rgba8Image { width: 600, height: 3, pixels: vec![0; 5] }), ..Default::default() }; + let (bytes, stats) = PcraftWriter::new().save_zip(&doc, &bad).unwrap(); + let zip = ZipReader::new(&bytes).unwrap(); + assert!(zip.read_by_name(FULL_COMPOSITE, usize::MAX).is_err()); + assert_eq!(zip.read_by_name(THUMB, usize::MAX).unwrap(), png(&thumb).unwrap()); + assert_eq!(crate::read_manifest(&bytes).unwrap().full_composite, None); + assert_eq!(stats.manifest_bytes, zip.read_by_name(MANIFEST, usize::MAX).unwrap().len()); + let dir = std::env::temp_dir().join(format!("pcraft-bad-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + PcraftWriter::new().save_dir(&doc, &dir, &bad).unwrap(); + assert!(!dir.join(FULL_COMPOSITE).exists()); + assert!(!std::fs::read_to_string(dir.join(MANIFEST)).unwrap().contains("full_composite")); + std::fs::remove_dir_all(&dir).unwrap(); let dir = std::env::temp_dir().join(format!("pcraft-previews-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); @@ -1364,11 +1397,10 @@ fn zip_save_leaves_the_full_composite_out_past_the_zip_limit() { ..Default::default() }; let (whole, _) = PcraftWriter::new().save_zip(&doc, &opts).unwrap(); - // The archive's entries without the central directory, and how many there are: what the + // The whole archive, central directory included, and how many entries it holds: what the // limit compares. - let archive = ZipReader::new(&whole).unwrap(); - let bytes = archive.entries.iter().map(|e| 30 + e.name.len() as u64 + archive.read(e, usize::MAX).unwrap().len() as u64).sum::(); - let count = archive.entries.len(); + let bytes = whole.len() as u64; + let count = ZipReader::new(&whole).unwrap().entries.len(); let (fits, _) = PcraftWriter::new().save_zip_within(&doc, &opts, (bytes, count)).unwrap(); assert_eq!(fits, whole, "an archive at the limit keeps the composite"); for limit in [(bytes - 1, count), (bytes, count - 1)] { From 78982a38e212288ee82b62ad1ac08641d25372e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 06:29:05 -0700 Subject: [PATCH 3/8] Scorecard: count the full-size composite preference after the merge of main --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 73e1bca3256..233167b9569 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 45 | 79 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 41 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 182 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 183 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -203,7 +203,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 182** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 12 of 183** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 69912e603575616748a0b67d8f518b6d8c6231b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 06:46:33 -0700 Subject: [PATCH 4/8] Format: the full-size composite stays within 2^26 pixels, and running out of memory leaves it out A canvas over 2^26 pixels (256 MiB of RGBA8) is saved without composite/full.png. The PNG encoder's buffers are reserved fallibly, so an allocation failure reports an encode error, and a ZIP bundle that cannot be reserved with the composite is written without it. --- book/src/formats/pcraft.md | 2 +- crates/codecs/src/codecs/png.rs | 39 ++++++++++++++++----- crates/format/src/store.rs | 19 ++++++++-- crates/io/src/lib.rs | 7 ++-- crates/io/tests/it/pcraft_full_composite.rs | 11 ++++++ 5 files changed, 63 insertions(+), 15 deletions(-) diff --git a/book/src/formats/pcraft.md b/book/src/formats/pcraft.md index 43abc198408..8a0e40a5a22 100644 --- a/book/src/formats/pcraft.md +++ b/book/src/formats/pcraft.md @@ -14,7 +14,7 @@ save.lock `thumb.png` (at most 256 px on the longer side), `composite/preview.png` (at most 1024 px) and `composite/full.png` (the canvas size) are the flattened document as 8-bit RGBA PNGs, whatever the document's depth. The manifest names each one it holds, under `thumbnail`, `composite` and `full_composite`. -A save writes `composite/full.png` only when it is asked to: *Save Full-Size Composite in .pcraft Files* in Preferences › File Handling for the app's saves, `"pcraftFullComposite": true` for the engine's `file.saveACopy` and its batch and export commands, and for the automation `doc.save` and MCP `doc_save`, and `--pcraft-full-composite` for `photocraft-cli convert`, `run` and `batch`. It is off by default. `composite/full.png` embeds the ICC profile of its pixels: an RGB document's own profile, a grayscale document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable profile. A save leaves it out when the canvas is larger than 2^30 pixels, when its pixels cannot be allocated or encoded, or when a ZIP bundle would pass 4 GiB or 65,535 entries with it. A directory bundle saved without it has the file from an earlier save removed. +A save writes `composite/full.png` only when it is asked to: *Save Full-Size Composite in .pcraft Files* in Preferences › File Handling for the app's saves, `"pcraftFullComposite": true` for the engine's `file.saveACopy` and its batch and export commands, and for the automation `doc.save` and MCP `doc_save`, and `--pcraft-full-composite` for `photocraft-cli convert`, `run` and `batch`. It is off by default. `composite/full.png` embeds the ICC profile of its pixels: an RGB document's own profile, a grayscale document's gray profile as RGB, and sRGB for CMYK, Lab and documents without a usable profile. A save leaves it out when the canvas is larger than 2^26 pixels, when its pixels cannot be allocated or encoded, or when a ZIP bundle would pass 4 GiB or 65,535 entries with it. A directory bundle saved without it has the file from an earlier save removed. `save.lock` exists only in directory bundles: a save holds an OS file lock on it while it writes objects, publishes the manifest and removes unreferenced objects, so concurrent saves of one bundle take turns. It is empty, and readers ignore it. diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index e119e22548d..1d91604abfe 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -1,7 +1,7 @@ //! PNG via the `png` crate directly: 8/16-bit, Adam7 read (and write), //! iCCP, eXIf, tEXt/zTXt/iTXt (XMP in `XML:com.adobe.xmp`), pHYs. -use std::io::{Cursor, Write}; +use std::io::{self, Cursor, Write}; use crate::Format; use crate::error::CodecError; @@ -303,6 +303,21 @@ fn is_latin1_keyword(k: &str) -> bool { !k.is_empty() && k.len() <= 79 && k.chars().all(|c| (' '..='~').contains(&c) || ('\u{a1}'..='\u{ff}').contains(&c)) } +/// Makes the PNG writer's output growth report an encode error on allocation failure. +struct FallibleOutput<'a>(&'a mut Vec); + +impl Write for FallibleOutput<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0.try_reserve(bytes.len()).map_err(|_| io::Error::other("not enough memory for PNG output"))?; + self.0.extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { let img = src.converted(plan.layout, plan.sample); let (w, h) = img.dimensions(); @@ -314,7 +329,8 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result PngRows { let prev = (!self.prev.is_empty()).then_some(self.prev.as_slice()); let parts = deflate_rows(rows, prev, stride, bpp, per_band, deflate_level(self.level), finish, encode_threads()) .ok_or_else(|| CodecError::encode(F, "a band of rows could not be compressed"))?; - let mut zlib = Vec::with_capacity(parts.iter().map(|p| p.z.len()).sum::() + 6); + let mut zlib = Vec::new(); + zlib.try_reserve_exact(parts.iter().map(|p| p.z.len()).sum::() + 6).map_err(|_| CodecError::encode(F, "not enough memory for PNG data"))?; if !self.started { zlib.extend_from_slice(&zlib_header(self.level)); self.started = true; @@ -530,7 +547,8 @@ impl PngRows { fn adam7_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression) -> Result, CodecError> { // (x0, y0, dx, dy) per pass. const PASSES: [(usize, usize, usize, usize); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]; - let mut raw = Vec::with_capacity(data.len() + h * 7); + let mut raw = Vec::new(); + raw.try_reserve_exact(data.len() + h * 7).map_err(|_| CodecError::encode(F, "not enough memory for PNG rows"))?; for (x0, y0, dx, dy) in PASSES { if x0 >= w || y0 >= h { continue; @@ -611,7 +629,8 @@ fn encode_threads() -> usize { fn banded_idat(data: &[u8], w: usize, h: usize, bpp: usize, level: PngCompression, threads: usize) -> Option> { let stride = w * bpp; let parts = deflate_rows(data.get(..h * stride)?, None, stride, bpp, band_rows(stride), deflate_level(level), true, threads)?; - let mut out = Vec::with_capacity(parts.iter().map(|p| p.z.len()).sum::() + 6); + let mut out = Vec::new(); + out.try_reserve_exact(parts.iter().map(|p| p.z.len()).sum::() + 6).ok()?; out.extend_from_slice(&zlib_header(level)); let mut adler = 1u32; for p in &parts { @@ -648,8 +667,11 @@ fn deflate_rows( let h = rows.len() / stride.max(1); let bands: Vec<(usize, usize)> = (0..h).step_by(band_rows.max(1)).map(|y| (y, (y + band_rows).min(h))).collect(); let band = |&(y0, y1): &(usize, usize)| -> Option { - let mut filtered = Vec::with_capacity((y1 - y0) * (stride + 1)); - let mut scratch = vec![0u8; stride]; + let mut filtered = Vec::new(); + filtered.try_reserve_exact((y1 - y0) * (stride + 1)).ok()?; + let mut scratch = Vec::new(); + scratch.try_reserve_exact(stride).ok()?; + scratch.resize(stride, 0); for y in y0..y1 { let row = rows.get(y * stride..(y + 1) * stride)?; let above = if y > 0 { rows.get((y - 1) * stride..y * stride) } else { prev }; @@ -696,7 +718,8 @@ fn deflate_rows( fn deflate_band(filtered: &[u8], lvl: flate2::Compression, last: bool) -> Option> { let mut c = flate2::Compress::new(lvl, false); // Stored blocks cost 5 bytes per 64 KiB, the flush an empty stored block: 1/8 is ample. - let mut z = Vec::with_capacity(filtered.len() + filtered.len() / 8 + 1024); + let mut z = Vec::new(); + z.try_reserve_exact(filtered.len() + filtered.len() / 8 + 1024).ok()?; let flush = if last { flate2::FlushCompress::Finish } else { flate2::FlushCompress::Sync }; let status = c.compress_vec(filtered, &mut z, flush).ok()?; let done = if last { status == flate2::Status::StreamEnd } else { c.total_in() as usize == filtered.len() && z.len() < z.capacity() }; diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 4c750afd982..cb2fcc5b35f 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -69,7 +69,7 @@ fn png(img: &Rgba8Image) -> Result> { /// [`png`] with `icc` embedded. fn png_tagged(img: &Rgba8Image, icc: Option<&[u8]>) -> Result> { let mut pixels = Vec::new(); - pixels.try_reserve_exact(img.pixels.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for preview".into()))?; + pixels.try_reserve_exact(img.pixels.len()).map_err(|_| FormatError::LimitExceeded("not enough memory for PNG pixels".into()))?; pixels.extend_from_slice(&img.pixels); let image = photocraft_codecs::Image::from_u8(img.width, img.height, photocraft_codecs::ChannelLayout::Rgba, pixels) .map_err(|e| FormatError::Unsupported(format!("preview: {e}")))? @@ -1033,11 +1033,11 @@ impl PcraftWriter { + previews.iter().map(|(name, data)| stored(name, data.len())).sum::() + entries.iter().map(|(path, _, data)| stored(path, data.len())).sum::(); let mut manifest = p.manifest; + let mut model = p.model; if (total > limit.0 || 1 + previews.len() + entries.len() > limit.1) && let Some(at) = previews.iter().position(|(name, _)| *name == FULL_COMPOSITE) { previews.remove(at); - let mut model = p.model; model.full_composite = None; manifest = manifest_json(&model)?; stats.manifest_bytes = manifest.len(); @@ -1047,7 +1047,20 @@ impl PcraftWriter { let sizes = std::iter::once((MANIFEST, manifest.len())) .chain(previews.iter().map(|(name, data)| (*name, data.len()))) .chain(entries.iter().map(|(path, _, data)| (path.as_str(), data.len()))); - let mut z = ZipWriter::with_entries(sizes)?; + let mut z = match ZipWriter::with_entries(sizes) { + Ok(z) => z, + Err(FormatError::LimitExceeded(_)) if previews.iter().any(|(name, _)| *name == FULL_COMPOSITE) => { + previews.retain(|(name, _)| *name != FULL_COMPOSITE); + model.full_composite = None; + manifest = manifest_json(&model)?; + stats.manifest_bytes = manifest.len(); + let sizes = std::iter::once((MANIFEST, manifest.len())) + .chain(previews.iter().map(|(name, data)| (*name, data.len()))) + .chain(entries.iter().map(|(path, _, data)| (path.as_str(), data.len()))); + ZipWriter::with_entries(sizes)? + } + Err(e) => return Err(e), + }; z.add(MANIFEST, &manifest)?; for (name, data) in &previews { z.add(name, data)?; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 5f0941fab18..a7cf4c1eddb 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -573,6 +573,8 @@ pub(crate) fn with_span(ctl: &photocraft_raster::Interrupt, lo: f32, hi: f32, const PCRAFT_THUMBNAIL_DONE: f32 = 0.15; const PCRAFT_PREVIEWS_DONE: f32 = 0.4; const PCRAFT_FULL_COMPOSITE_DONE: f32 = 0.6; +/// Bounds the optional full-size RGBA8 composite to 256 MiB before PNG and ZIP encoding. +const PCRAFT_FULL_COMPOSITE_PIXELS: u64 = 1 << 26; /// The share of a PSD/PSB export spent converting the document (layers, then the composite) /// before its bytes are assembled: about 2.7 s of 3.0 s for a 24 MP, 5-layer RGB/8 document. const PSD_MODEL_DONE: f32 = 0.9; @@ -660,8 +662,7 @@ fn export_stages(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: & /// The flattened document at its canvas size, in 8-bit RGBA like a `.pcraft` file's two previews, /// for the bundle's `composite/full.png`. `None` for a canvas past -/// [`photocraft_compose::MAX_RENDER_PIXELS`], or when its pixels cannot be allocated (a 32-bit -/// target holds less than 2 GiB in one buffer). +/// 2^26 pixels, or when its pixels cannot be allocated. pub fn pcraft_full_composite(doc: &Document) -> Option { pcraft_full_composite_with(doc, &photocraft_raster::Interrupt::NONE).ok().flatten() } @@ -683,7 +684,7 @@ pub fn pcraft_full_composite_icc(doc: &Document) -> Vec { /// cancelled render fails with [`IoError::Cancelled`]. fn pcraft_full_composite_with(doc: &Document, ctl: &photocraft_raster::Interrupt) -> Result, IoError> { let canvas = doc.bounds(); - if canvas.is_empty() || u64::from(canvas.width()) * u64::from(canvas.height()) > photocraft_compose::MAX_RENDER_PIXELS { + if canvas.is_empty() || u64::from(canvas.width()) * u64::from(canvas.height()) > PCRAFT_FULL_COMPOSITE_PIXELS { return Ok(None); } let Ok(len) = usize::try_from(u64::from(canvas.width()) * u64::from(canvas.height()) * 4) else { return Ok(None) }; diff --git a/crates/io/tests/it/pcraft_full_composite.rs b/crates/io/tests/it/pcraft_full_composite.rs index f0710f7878b..260cf893b9a 100644 --- a/crates/io/tests/it/pcraft_full_composite.rs +++ b/crates/io/tests/it/pcraft_full_composite.rs @@ -129,3 +129,14 @@ fn a_canvas_past_the_render_limit_is_saved_without_it() { assert_eq!(photocraft_format::read_manifest(&bytes).expect("manifest").full_composite, None); assert!(ZipReader::new(&bytes).expect("zip").find("composite/full.png").is_none()); } + +#[test] +fn a_sparse_canvas_past_the_composite_memory_budget_is_saved_without_it() { + // The layer data stays tiny; an 8193 x 8192 RGBA8 composite exceeds 256 MiB. + let mut d = doc(64, 64, SampleType::U8); + d.size = Size::new(8193, 8192); + assert!(photocraft_io::pcraft_full_composite(&d).is_none()); + let bytes = export(&d, "a.pcraft", &on()).expect("export").bytes; + assert_eq!(photocraft_format::read_manifest(&bytes).expect("manifest").full_composite, None); + assert!(ZipReader::new(&bytes).expect("zip").find("composite/full.png").is_none()); +} From f121865ffaf8778f9c349bbc622fb059b1ada381 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 08:20:23 -0700 Subject: [PATCH 5/8] Docs: a .pcraft save can leave the full-size composite out The doc.save row, docs/development.md, the MCP doc_save description, the file.saveACopy params text, the --pcraft-full-composite help and the option's doc comments said the option writes composite/full.png. A save leaves it out when the canvas is past 2^26 pixels, when its pixels cannot be allocated or encoded, or when a ZIP bundle would pass its limits. They now say so and point to the manifest's full_composite member, which names the entry when it was written. --- apps/photocraft-cli/src/args.rs | 4 ++-- crates/automation/src/files.rs | 2 +- crates/automation/src/server.rs | 6 +++--- crates/engine/src/cmd/file_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/save.rs | 5 +++-- crates/io/src/lib.rs | 5 +++-- docs/control-protocol.md | 2 +- docs/development.md | 2 +- 8 files changed, 15 insertions(+), 13 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 66e2fbb3d7c..8c7b708b7de 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -74,8 +74,8 @@ pub(crate) struct ExportArgs { /// and CMYK shrink) or progressive #[arg(long, value_name = "baseline|optimized|progressive", value_parser = jpeg_format)] pub(crate) jpeg_format: Option, - /// Also write the flattened document at its canvas size into .pcraft output, as - /// composite/full.png + /// Request the flattened document at its canvas size in .pcraft output as + /// composite/full.png; it may be omitted. Check the manifest's full_composite member. #[arg(long)] pub(crate) pcraft_full_composite: bool, } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index 5f509a692c5..a74af992417 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -57,7 +57,7 @@ pub fn previews(doc: &Document) -> SaveOptions { SaveOptions { thumbnail: Some(photocraft_compose::thumbnail(doc, 256)), composite: Some(photocraft_compose::thumbnail(doc, 1024)), ..Default::default() } } -/// [`previews`], plus the full-size composite when `opts` asks for it +/// [`previews`], plus the full-size composite when `opts` asks for it and it can be rendered /// ([`ExportOptions::pcraft_full_composite`]). fn native_options(doc: &Document, opts: &ExportOptions) -> SaveOptions { let mut out = previews(doc); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 3ac8796cdf1..0b7c3fa753c 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -191,8 +191,8 @@ pub struct SaveParams { /// DDS: also write the full mip chain, each level a box filter of the one above. #[serde(default, rename = "ddsMipmaps")] pub dds_mipmaps: bool, - /// .pcraft: also write the flattened document at its canvas size as `composite/full.png`. - /// Off by default. + /// .pcraft: request the flattened document at its canvas size as `composite/full.png`. + /// The save may omit it; check the manifest's `full_composite` member. Off by default. #[serde(default, rename = "pcraftFullComposite")] pub pcraft_full_composite: Option, #[serde(default)] @@ -796,7 +796,7 @@ impl PhotocraftMcp { } #[tool(description = "Save the document. `.pcraft` is the lossless native format (incremental); other extensions \ - (psd, png, jpg, tif, webp, exr, …) export. Without `path` only a PSD, PSB or .pcraft document is written back to its own file. Returns warnings about anything the format cannot hold.")] + (psd, png, jpg, tif, webp, exr, …) export. Without `path` only a PSD, PSB or .pcraft document is written back to its own file. `pcraftFullComposite` requests `composite/full.png`, which may be omitted; check the manifest's `full_composite` member. Returns warnings about anything the format cannot hold.")] async fn doc_save(&self, Parameters(p): Parameters) -> Result { self.save_impl(p).await } diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 7ad6492dce7..ec411fee514 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -243,7 +243,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: also write the flattened document at its canvas size as composite/full.png; unset, Preferences › File Handling)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##, native_doc, save_a_copy ), diff --git a/crates/engine/src/cmd/file_cmds/save.rs b/crates/engine/src/cmd/file_cmds/save.rs index 96f04836898..9c073df8906 100644 --- a/crates/engine/src/cmd/file_cmds/save.rs +++ b/crates/engine/src/cmd/file_cmds/save.rs @@ -34,8 +34,9 @@ pub(crate) struct SaveOpts { /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB /// File Compatibility). pub psd_maximize_compatibility: bool, - /// `.pcraft`: also write the full-size composite (`"pcraftFullComposite"`; unset, Preferences › - /// File Handling › Save Full-Size Composite in .pcraft Files, off by default). + /// `.pcraft`: request the full-size composite (`"pcraftFullComposite"`; unset, Preferences › + /// File Handling › Save Full-Size Composite in .pcraft Files, off by default). The save may + /// omit it; check the manifest's `full_composite` member. pub pcraft_full_composite: bool, } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a7cf4c1eddb..37c10b601a2 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -240,8 +240,9 @@ pub struct ExportOptions { /// PSD/PSB and layered TIFF: read and embed the files linked smart objects name (see /// [`PsdExportOptions::read_linked_files`]). On by default; automation turns it off. pub read_linked_files: bool, - /// `.pcraft`: also write the flattened document at its canvas size as `composite/full.png` - /// (Preferences › File Handling › Save Full-Size Composite in .pcraft Files). Off by default. + /// `.pcraft`: request the flattened document at its canvas size as `composite/full.png` + /// (Preferences › File Handling › Save Full-Size Composite in .pcraft Files). The save may + /// omit it; check the manifest's `full_composite` member. Off by default. pub pcraft_full_composite: bool, } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 257fab8686c..b31337ca62b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -428,7 +428,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/development.md b/docs/development.md index 2e67b98283a..5d5a9217606 100644 --- a/docs/development.md +++ b/docs/development.md @@ -271,7 +271,7 @@ The `--cli` selector is removed; all remaining arguments, stdin, stdout, stderr - `manifest.json`: the versioned document tree, with migrations in `format/src/migrate.rs`. - `tiles/.zst` and `blobs/.zst`: zstd-compressed objects, content-addressed by the BLAKE3 hash of their uncompressed bytes. - `thumb.png` and `composite/preview.png`: previews. -- `composite/full.png`: the flattened document at the canvas size, for other apps that read `.pcraft` files. Saves write it only when asked (`ExportOptions::pcraft_full_composite`, off by default). +- `composite/full.png`: the flattened document at the canvas size, for other apps that read `.pcraft` files. Saves write it only when asked (`ExportOptions::pcraft_full_composite`, off by default), and may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md). Check the manifest's `full_composite` member to confirm it was written. - `save.lock` (directory bundles only): an empty file a save holds an OS file lock on, so two writers or processes saving one bundle take turns (#4957). Keep one `PcraftWriter` per open document: re-saving then only compresses and writes tiles that changed. Directory bundles verify objects on first encounter in a folder; later saves reuse them while their file size and modification time are unchanged, and re-verify changed objects, repair missing or damaged objects, and garbage-collect unreferenced ones. `format::Autosaver` writes snapshots into a recovery directory on a background thread. `list_recovery` / `recover` / `discard_recovery` implement crash recovery, and `format::RecoveryStore` is the lifecycle the desktop app uses: new documents autosave under per-launch keys (document ids restart every launch, so they never overwrite an older entry), and a recovered document adopts the entry it came from. That entry is replaced in place by the next autosave and removed only when the document is saved or closed, never just because it was recovered, so a second crash loses nothing. The web build has no crash recovery (no autosave services). From 24d4f4db9fea590ed7dde65db6592938359c2c2e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:27:12 -0500 Subject: [PATCH 6/8] Release 0.20.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 58c70d0228d..3751dbac4b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4973,7 +4973,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.19.0" +version = "0.20.0" dependencies = [ "arboard", "async-io", @@ -5028,7 +5028,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.19.0" +version = "0.20.0" dependencies = [ "crc32fast", "flate2", @@ -5038,7 +5038,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.19.0" +version = "0.20.0" dependencies = [ "criterion", "photocraft-color", @@ -5053,7 +5053,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.19.0" +version = "0.20.0" dependencies = [ "base64 0.23.1", "cap-std", @@ -5078,7 +5078,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.19.0" +version = "0.20.0" dependencies = [ "clap", "clap_complete", @@ -5097,7 +5097,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.19.0" +version = "0.20.0" dependencies = [ "moxcms", "rayon", @@ -5105,7 +5105,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.19.0" +version = "0.20.0" dependencies = [ "craft-jpeg", "exr", @@ -5129,7 +5129,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-cms", "serde", @@ -5137,7 +5137,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.19.0" +version = "0.20.0" dependencies = [ "criterion", "photocraft-cms", @@ -5153,7 +5153,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5164,7 +5164,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.19.0" +version = "0.20.0" dependencies = [ "base64 0.22.1", "blake3", @@ -5206,7 +5206,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.19.0" +version = "0.20.0" dependencies = [ "blake3", "craft-pcraft-format", @@ -5230,14 +5230,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.19.0" +version = "0.20.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.19.0" +version = "0.20.0" dependencies = [ "bytemuck", "half", @@ -5257,14 +5257,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.19.0" +version = "0.20.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.19.0" +version = "0.20.0" dependencies = [ "blake3", "craft-docpath", @@ -5300,18 +5300,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.19.0" +version = "0.20.0" [[package]] name = "photocraft-ops" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5325,7 +5325,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5341,7 +5341,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.19.0" +version = "0.20.0" dependencies = [ "encoding_rs", "flate2", @@ -5353,7 +5353,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5364,7 +5364,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.19.0" +version = "0.20.0" dependencies = [ "flate2", "image", @@ -5379,7 +5379,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.19.0" +version = "0.20.0" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -5391,7 +5391,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.19.0" +version = "0.20.0" dependencies = [ "memory-stats", "serde_json", @@ -5399,7 +5399,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.19.0" +version = "0.20.0" dependencies = [ "flate2", "parley", @@ -5414,7 +5414,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.19.0" +version = "0.20.0" dependencies = [ "base64 0.23.1", "craft-print", @@ -5459,7 +5459,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.19.0" +version = "0.20.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5470,7 +5470,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.19.0" +version = "0.20.0" dependencies = [ "eframe", "egui", @@ -5492,7 +5492,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.19.0" +version = "0.20.0" dependencies = [ "flate2", "js-sys", @@ -9220,7 +9220,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.19.0" +version = "0.20.0" dependencies = [ "chrono", "serde", diff --git a/Cargo.toml b/Cargo.toml index 4674a55e6fd..669e930777b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.19.0" +version = "0.20.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From eed8bd27d297b87ab33bde76f7196bfa6ecfc76e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:47:01 -0500 Subject: [PATCH 7/8] Packaging: run the cross-built CLI's --version check without the malloc re-exec Co-Authored-By: Claude Opus 5.5 --- packaging/linux/package.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 8b6cf54abed..519bc850c6f 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -208,7 +208,9 @@ fi if [[ -z "${CROSS_TARGET:-}" ]]; then "$STAGE/usr/bin/photocraft-cli" --version elif [[ -n "${EMULATOR:-}" ]]; then - "$EMULATOR" "$STAGE/usr/bin/photocraft-cli" --version + # Set, so malloc_tuning::apply doesn't re-execute the CLI (#8743): under qemu-user that exec goes + # to the host kernel, which can't run a $CROSS_ARCH binary, and glibc then hands it to /bin/sh. + MALLOC_TRIM_THRESHOLD_=131072 "$EMULATOR" "$STAGE/usr/bin/photocraft-cli" --version fi echo "==> done" ls -lh "$DIST" From 327c4cc82e737a3e0af7c147a477126d77525495 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 2 Nov 2026 19:47:05 -0500 Subject: [PATCH 8/8] Release 0.20.1 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3751dbac4b6..27fbbbc09c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4973,7 +4973,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.20.0" +version = "0.20.1" dependencies = [ "arboard", "async-io", @@ -5028,7 +5028,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.20.0" +version = "0.20.1" dependencies = [ "crc32fast", "flate2", @@ -5038,7 +5038,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.20.0" +version = "0.20.1" dependencies = [ "criterion", "photocraft-color", @@ -5053,7 +5053,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.20.0" +version = "0.20.1" dependencies = [ "base64 0.23.1", "cap-std", @@ -5078,7 +5078,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.20.0" +version = "0.20.1" dependencies = [ "clap", "clap_complete", @@ -5097,7 +5097,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.20.0" +version = "0.20.1" dependencies = [ "moxcms", "rayon", @@ -5105,7 +5105,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-jpeg", "exr", @@ -5129,7 +5129,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-cms", "serde", @@ -5137,7 +5137,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.20.0" +version = "0.20.1" dependencies = [ "criterion", "photocraft-cms", @@ -5153,7 +5153,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5164,7 +5164,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.20.0" +version = "0.20.1" dependencies = [ "base64 0.22.1", "blake3", @@ -5206,7 +5206,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.20.0" +version = "0.20.1" dependencies = [ "blake3", "craft-pcraft-format", @@ -5230,14 +5230,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.20.0" +version = "0.20.1" dependencies = [ "bytemuck", "half", @@ -5257,14 +5257,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.20.0" +version = "0.20.1" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.20.0" +version = "0.20.1" dependencies = [ "blake3", "craft-docpath", @@ -5300,18 +5300,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.20.0" +version = "0.20.1" [[package]] name = "photocraft-ops" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5325,7 +5325,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5341,7 +5341,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.20.0" +version = "0.20.1" dependencies = [ "encoding_rs", "flate2", @@ -5353,7 +5353,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5364,7 +5364,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flate2", "image", @@ -5379,7 +5379,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.20.0" +version = "0.20.1" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -5391,7 +5391,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.20.0" +version = "0.20.1" dependencies = [ "memory-stats", "serde_json", @@ -5399,7 +5399,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flate2", "parley", @@ -5414,7 +5414,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.20.0" +version = "0.20.1" dependencies = [ "base64 0.23.1", "craft-print", @@ -5459,7 +5459,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.20.0" +version = "0.20.1" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5470,7 +5470,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.20.0" +version = "0.20.1" dependencies = [ "eframe", "egui", @@ -5492,7 +5492,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flate2", "js-sys", @@ -9220,7 +9220,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "serde", diff --git a/Cargo.toml b/Cargo.toml index 669e930777b..e01bcf175ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.20.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95"