diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 91b99ef33b9..8c7b708b7de 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, + /// 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, } /// 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 fcc93e06a03..176fb970fdb 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_full_composite(&std::fs::read(path).unwrap()).unwrap().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..8a0e40a5a22 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^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. 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..a74af992417 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 and it can be rendered +/// ([`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 92ece2b943b..7ccf168055e 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -126,8 +126,14 @@ 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: 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()))?; 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 544dbc90f15..0b7c3fa753c 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: 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)] pub index: Option, } @@ -792,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 } @@ -1079,6 +1083,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.is_some().then_some("pcraftFullComposite"), dpx_bits.is_some().then_some("dpxBits"), p.index.is_some().then_some("index"), ] @@ -1105,7 +1110,12 @@ 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.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/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/mcp.rs b/crates/automation/tests/it/mcp.rs index e18df63c4a0..13f1195a172 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -360,6 +360,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 new file mode 100644 index 00000000000..f699087cc62 --- /dev/null +++ b/crates/automation/tests/it/native_full_composite.rs @@ -0,0 +1,49 @@ +//! 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 png = photocraft_format::read_full_composite(bytes).unwrap().expect("the manifest names the full-size composite"); + let image = photocraft_codecs::decode(&png).unwrap(); + (image.dimensions(), image.to_rgba8()) +} + +fn has_full_composite(bytes: &[u8]) -> bool { + photocraft_format::read_full_composite(bytes).unwrap().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)); + 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/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/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 82a54214452..f15e8bb827a 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -53,7 +53,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; @@ -244,7 +246,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: 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 fff62dc7f46..9c073df8906 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,10 @@ 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`: 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, } impl Default for SaveOpts { @@ -47,6 +52,7 @@ impl Default for SaveOpts { dds: photocraft_io::DdsOptions::default(), image_previews: true, psd_maximize_compatibility: true, + pcraft_full_composite: false, } } } @@ -56,7 +62,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 +76,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: pcraft_full_composite_param(p, cmd)?.unwrap_or(file_handling.pcraft_full_composite), }) } @@ -98,6 +106,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> { @@ -178,6 +198,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 03e7fabe89b..ff3949918bc 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -456,6 +456,37 @@ 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_full_composite(&std::fs::read(path).unwrap()).unwrap().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); + } + 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] 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 80622e305df..786295d1a78 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -493,6 +493,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, @@ -525,6 +528,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 cb1c5eb41d3..b1e889c1b83 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) //! ``` //! @@ -98,6 +99,12 @@ 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, 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>, } /// Limits applied while loading untrusted bundles. @@ -212,3 +219,14 @@ pub fn read_thumbnail(bytes: &[u8]) -> Result>> { None => Ok(None), } } + +/// The embedded full-size composite (PNG bytes): `None` when the manifest has no +/// `full_composite` member. A member that names any entry other than `composite/full.png` is +/// refused. +pub fn read_full_composite(bytes: &[u8]) -> Result>> { + let src = store::ZipSource::new(bytes)?; + match store::read_full_composite_entry(&src, &LoadOptions::default())? { + Some(p) => Ok(Some(src.get(p, bytes.len())?)), + None => Ok(None), + } +} diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index dd3a012ad2d..5d725b6bf29 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -17,7 +17,9 @@ use serde::{Deserialize, Serialize}; pub use craft_pcraft_format::{FORMAT_VERSION, Hash, TileRef}; /// The manifest: craft-pcraft-format's envelope (`format_version`, `generator`, the optional -/// `thumbnail` and `composite` previews) around the document [`DocM`]. +/// `thumbnail` and `composite` previews) around the document [`DocM`]. A save with the full-size +/// composite adds a `full_composite` member after the envelope; [`crate::read_full_composite`] +/// reads it. pub type Manifest = craft_pcraft_format::Manifest; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 5fa9b55425f..eeb082954c8 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -18,6 +18,14 @@ use crate::{FormatError, LoadOptions, Result, SaveOptions}; use craft_pcraft_format::{BLOBS_DIR, COMPOSITE_DIR, TILES_DIR, blob_path, tile_path}; // `SAVE_LOCK` is the file a directory save holds an exclusive lock on for its whole transaction (#4957). pub(crate) use craft_pcraft_format::{COMPOSITE, MANIFEST, SAVE_LOCK, THUMB}; +/// The flattened document at its canvas size, a PNG in [`COMPOSITE_DIR`], named by the manifest's +/// `full_composite` member. +pub(crate) const FULL_COMPOSITE: &str = "composite/full.png"; +/// The manifest member that names [`FULL_COMPOSITE`]. +const FULL_COMPOSITE_MEMBER: &str = "full_composite"; +/// 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); /// How long a directory save waits for another save of the same bundle to finish. const SAVE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10); @@ -129,16 +137,31 @@ fn hash_bytes(b: &[u8]) -> Hash { } fn png(img: &Rgba8Image) -> 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}")))?; + png_tagged(img, None) +} + +/// [`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 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}")))? + .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? { @@ -147,6 +170,10 @@ fn previews(opts: &SaveOptions) -> Result)>> { if let Some(t) = composite? { out.push((COMPOSITE, t)); } + // 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) } @@ -230,6 +257,43 @@ fn manifest_limits(max_manifest_bytes: usize) -> craft_pcraft_format::Limits { limits } +/// The manifest as a save writes it: `manifest`, followed by a `full_composite` member naming +/// [`FULL_COMPOSITE`] when `full_composite` is set. Without it the bytes are `manifest`'s own. +fn manifest_json(manifest: &Manifest, full_composite: bool) -> Result> { + #[derive(serde::Serialize)] + struct WithFullComposite<'a> { + #[serde(flatten)] + manifest: &'a Manifest, + full_composite: &'static str, + } + // 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 = if full_composite { + serde_json::to_vec_pretty(&WithFullComposite { manifest, full_composite: FULL_COMPOSITE })? + } else { + serde_json::to_vec_pretty(manifest)? + }; + // The nesting and the items only: a save checks no manifest size. + craft_pcraft_format::check_manifest(&json, &manifest_limits(usize::MAX))?; + Ok(json) +} + +/// The entry the manifest's `full_composite` member names: `None` when the member is missing or +/// `null`. A member that names any entry other than [`FULL_COMPOSITE`] is refused. +pub(crate) fn read_full_composite_entry(src: &dyn ByteSource, opts: &LoadOptions) -> Result> { + let raw = src.get(MANIFEST, opts.max_manifest_bytes)?; + let manifest = craft_pcraft_format::parse_manifest(&raw, &manifest_limits(opts.max_manifest_bytes))?; + match manifest.get(FULL_COMPOSITE_MEMBER) { + None | Some(serde_json::Value::Null) => Ok(None), + Some(serde_json::Value::String(entry)) if entry == FULL_COMPOSITE => Ok(Some(FULL_COMPOSITE)), + Some(other) => Err(FormatError::corrupt(format!("`{FULL_COMPOSITE_MEMBER}` names {other}, not {FULL_COMPOSITE:?}"))), + } +} + pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result { let raw = src.get(MANIFEST, opts.max_manifest_bytes)?; // serde_json stops at 128 levels (about 40 nested groups); `read_manifest_with` checks the @@ -549,10 +613,26 @@ struct FileSignature { struct Prepared { manifest: Vec, + /// What `manifest` encodes, for a ZIP save that has to leave the full-size composite out. + model: Manifest, + /// Whether `manifest` names the full-size composite. + full_composite: bool, objects: BTreeMap, 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.full_composite && !previews.iter().any(|(name, _)| *name == FULL_COMPOSITE) { + self.full_composite = false; + self.manifest = manifest_json(&self.model, false)?; + self.stats.manifest_bytes = self.manifest.len(); + } + Ok(()) + } +} + enum Object { Tile(Arc, SampleType), Blob(Arc>), @@ -826,6 +906,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_DIR, name)) if name.strip_suffix(craft_pcraft_format::OBJECT_SUFFIX).is_some_and(is_valid_hash) => (&self.tiles, name), Some((BLOBS_DIR, name)) if name.strip_suffix(craft_pcraft_format::OBJECT_SUFFIX).is_some_and(is_valid_hash) => (&self.blobs, name), @@ -952,18 +1033,11 @@ impl PcraftWriter { convert::check_nesting(&doc.layers)?; let mut c = Collect { hash_cache: Some(&mut self.hash_cache), blob_hash_cache: Some(&mut self.blob_hash_cache), ..Default::default() }; let document = convert::doc_m(doc, &mut c); - let mut manifest = Manifest::new(format!("photocraft-format {}", env!("CARGO_PKG_VERSION")), document); - manifest.thumbnail = opts.thumbnail.as_ref().map(|_| THUMB.to_owned()); - manifest.composite = opts.composite.as_ref().map(|_| 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)?; - // The nesting and the items only: a save checks no manifest size. - craft_pcraft_format::check_manifest(&manifest, &manifest_limits(usize::MAX))?; + let mut model = Manifest::new(format!("photocraft-format {}", env!("CARGO_PKG_VERSION")), document); + model.thumbnail = opts.thumbnail.as_ref().map(|_| THUMB.to_owned()); + model.composite = opts.composite.as_ref().map(|_| COMPOSITE.to_owned()); + let full_composite = opts.full_composite.is_some(); + let manifest = manifest_json(&model, full_composite)?; let stats = SaveStats { tiles_total: c.tiles.len(), blobs_total: c.blobs.len(), manifest_bytes: manifest.len(), ..Default::default() }; let invalid = |h: &str| FormatError::corrupt(format!("invalid object hash `{h}`")); let mut objects = BTreeMap::new(); @@ -973,15 +1047,21 @@ impl PcraftWriter { for (h, b) in c.blobs { objects.insert(blob_path(&h).ok_or_else(|| invalid(&h))?, Object::Blob(b)); } - Ok(Prepared { manifest, objects, stats }) + Ok(Prepared { manifest, model, full_composite, 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)?; @@ -990,23 +1070,11 @@ impl PcraftWriter { Ok((p, fresh)) }, ); - let (p, mut fresh) = prepared?; - let previews = previews?; + let (mut p, mut fresh) = prepared?; + let mut previews = previews?; + p.match_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()); let mut compressor: Option = None; for (path, obj) in &p.objects { let (key, data) = match self.compressed.remove_entry(path) { @@ -1024,6 +1092,49 @@ impl PcraftWriter { (None, fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed(compressor.get_or_insert_with(Compressor::new))))) } }; + entries.push((path, key, data)); + } + // 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; + if (total > limit.0 || 1 + previews.len() + entries.len() > limit.1) + && let Some(at) = previews.iter().position(|(name, _)| *name == FULL_COMPOSITE) + { + previews.remove(at); + manifest = manifest_json(&p.model, false)?; + 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 = 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); + manifest = manifest_json(&p.model, false)?; + 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)?; + } + 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(); @@ -1051,11 +1162,12 @@ 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)?; + 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() }); @@ -1142,7 +1254,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); } @@ -1289,35 +1401,102 @@ 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_full_composite(&bytes).unwrap(), opts.full_composite.as_ref().map(|i| png(i).unwrap())); } - 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"))); + // 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_full_composite(&bytes).unwrap(), 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); - 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 whole archive, central directory included, and how many entries it holds: what the + // limit compares. + 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)] { + 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 be016f0aaf6..062a755bf0a 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -497,7 +497,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(); @@ -509,6 +509,45 @@ 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(); + assert!(read_full_composite(&bytes).unwrap().is_some()); + assert_eq!(read_manifest(&bytes).unwrap().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_full_composite(&older).unwrap(), None); + // A member that names any other entry is refused, and the document still opens. + manifest["full_composite"] = serde_json::Value::from("thumb.png"); + 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") { + z.add(&e.name, &r.read(e, usize::MAX).unwrap()).unwrap(); + } + let other = z.finish().unwrap(); + assert!(read_full_composite(&other).is_err()); + assert_eq!(load_from_bytes(&other).unwrap(), doc); + 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); @@ -536,7 +575,7 @@ fn save_is_deterministic() { fn save_load_save_gives_the_same_bytes() { let mut preview = Rgba8Image::new(4, 3); preview.pixels.iter_mut().enumerate().for_each(|(i, p)| *p = i as u8); - for opts in [SaveOptions::default(), SaveOptions { thumbnail: Some(preview.clone()), composite: Some(preview.clone()) }] { + for opts in [SaveOptions::default(), SaveOptions { thumbnail: Some(preview.clone()), composite: Some(preview.clone()), ..Default::default() }] { for mode in MODES { for depth in SampleType::ALL { let first = save_to_bytes(&rich_doc(mode, depth), &opts).unwrap(); @@ -934,7 +973,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(); @@ -954,7 +993,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"]; @@ -985,7 +1024,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 d9bb69af2cd..1a1e3b41e19 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -251,6 +251,11 @@ 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`: 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 ([`photocraft_format::read_full_composite`] + /// reads it). Off by default. + pub pcraft_full_composite: bool, } impl Default for ExportOptions { @@ -266,6 +271,7 @@ impl Default for ExportOptions { document_path: None, pcraft_cache: None, read_linked_files: true, + pcraft_full_composite: false, } } } @@ -612,9 +618,13 @@ 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; +/// 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; @@ -649,7 +659,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)?, @@ -693,6 +710,55 @@ 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 +/// 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() +} + +/// 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()) > 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) }; + 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 49262bc9b17..2280e2d7d9c 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -41,6 +41,7 @@ mod multichannel; mod native_vector_preview; 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..65acccdcd5e --- /dev/null +++ b/crates/io/tests/it/pcraft_full_composite.rs @@ -0,0 +1,140 @@ +//! 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 png = photocraft_format::read_full_composite(bytes).expect("manifest").expect("the manifest names the full-size composite"); + assert_eq!(png, ZipReader::new(bytes).expect("zip").read_by_name("composite/full.png", 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_full_composite(&bytes).expect("manifest"), 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_full_composite(&bytes).expect("manifest"), 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_full_composite(&bytes).expect("manifest"), 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 2fee62f41ef..27d61ddeadf 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -355,14 +355,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 704517c867d..6b84a31cbf3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3969,6 +3969,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 Edit Selected Guides Upravit vybraná vodítka Clear Selected Guides Vymazat vybraná vodítka Bicubic Automatic Bikubická automatická diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 49ef4a86ff3..c68e8e098db 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3368,6 +3368,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 Color Profile Farbprofil EXIF EXIF Edit Selected Guides Ausgewählte Hilfslinien bearbeiten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2b154f6c0b0..e40e24e130a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4052,6 +4052,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 EXIF EXIF Edit Selected Guides Επεξεργασία επιλεγμένων οδηγών Clear Selected Guides Απαλοιφή επιλεγμένων οδηγών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45bb9167164..4b039176f41 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4265,6 +4265,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 Edit Selected Guides Editar guías seleccionadas Clear Selected Guides Borrar guías seleccionadas Bicubic Automatic Bicúbica automática diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3c45f01228e..c9e3bf5d3d5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3359,6 +3359,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 Edit Selected Guides Modifier les repères sélectionnés Clear Selected Guides Effacer les repères sélectionnés Bicubic Automatic Bicubique automatique diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f77ec930efb..37e07e1690f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4244,6 +4244,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 Edit Selected Guides Kijelölt segédvonalak szerkesztése Clear Selected Guides Kijelölt segédvonalak törlése Bicubic Automatic Automatikus bikubikus diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 09d37cf787f..5d1a13dcc83 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3364,6 +3364,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 Edit Selected Guides Edit Panduan Terpilih Clear Selected Guides Hapus Panduan Terpilih Bicubic Automatic Bicubic otomatis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d66b0499bb4..6c2d6c18cd3 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4315,6 +4315,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 Adobe-rgb-compat Adobe RGB (compatibile) All shortcuts reset to Photoshop defaults. Tutte le scorciatoie ripristinate ai predefiniti di Photoshop. Arc Lower Arco inferiore diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 4bd69f5e9c6..0d3714c9e2e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4027,6 +4027,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ファイルにフルサイズの合成画像を保存 Edit Selected Guides 選択したガイドを編集 Clear Selected Guides 選択したガイドを消去 Bicubic Automatic バイキュービック法 (自動) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5f63b607480..c52d0c31ca9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3558,6 +3558,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 파일에 전체 크기 합성 이미지 저장 Color Profile 색상 프로필 EXIF EXIF Edit Selected Guides 선택한 안내선 편집 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2914efc01a3..c80142366a6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4111,6 +4111,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 Edit Selected Guides Geselecteerde hulplijnen bewerken Clear Selected Guides Geselecteerde hulplijnen wissen Bicubic Automatic Bicubisch automatisch diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5092ea491d1..1b5c9e68788 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3968,6 +3968,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 Edit Selected Guides Edytuj zaznaczone prowadnice Clear Selected Guides Usuń zaznaczone prowadnice Bicubic Automatic Dwusześcienna automatyczna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1077f10eca..7b50d472fe0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4151,6 +4151,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 Edit Selected Guides Editar guias selecionadas Clear Selected Guides Limpar guias selecionadas Bicubic Automatic Bicúbica automática diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index a7f45fbc7a3..487a6fc0660 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3332,6 +3332,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 Edit Selected Guides Изменить выбранные направляющие Clear Selected Guides Удалить выбранные направляющие Bicubic Automatic Бикубическая, автоматически diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index a3baa8e723d..0152204d905 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4396,6 +4396,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 Edit Selected Guides Uredi izabrane vodilje Clear Selected Guides Ukloni izabrane vodilje diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 14360176cdf..a45309f6b29 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4051,6 +4051,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 Edit Selected Guides Seçili Kılavuzları Düzenle Clear Selected Guides Seçili Kılavuzları Temizle Bicubic Automatic Bikübik Otomatik diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ededaa1dad9..eec0b45c31c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4054,6 +4054,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 Edit Selected Guides Редагувати вибрані напрямні Clear Selected Guides Очистити вибрані напрямні Bicubic Automatic Бікубічна, автоматично diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9219475c88e..768d1dd2adb 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3820,6 +3820,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 Edit Selected Guides Sửa đường căn đã chọn Clear Selected Guides Xóa đường căn đã chọn Bicubic Automatic Bicubic tự động diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ef27882217d..2a203c08c12 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3009,6 +3009,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 文件中存储全尺寸合成图像 Color Profile 颜色配置文件 EXIF EXIF Edit Selected Guides 编辑所选参考线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c0bb1a3abfb..6452c838bd0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2970,6 +2970,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 檔案中儲存全尺寸合成影像 Color Profile 色彩描述檔 EXIF EXIF Edit Selected Guides 編輯所選參考線 diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 2258a3f7be5..2b477a3c1e3 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 d770d4a6010..8859fb606cd 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -92,6 +92,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, @@ -121,6 +124,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, @@ -151,6 +155,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 7c5f4f2c242..609363ca9d4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -449,7 +449,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`; 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 4e5dfa77fb0..3b15282761a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -273,6 +273,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), 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). diff --git a/docs/scorecard.md b/docs/scorecard.md index 32cc47bfd57..a4b9635f0f6 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: 11 of 183 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 11 of 184 (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: 11 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. +**Settings that do nothing: 11 of 184** (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.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`.