From 2aa88b0956f47048a08813f3bdcb99b06b748e62 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 26 Oct 2026 19:19:10 +0000 Subject: [PATCH] refactor(io): split psd_export.rs into psd_export/ --- crates/io/src/psd_export.rs | 1044 +------------------------ crates/io/src/psd_export/document.rs | 391 +++++++++ crates/io/src/psd_export/estimate.rs | 135 ++++ crates/io/src/psd_export/merged.rs | 143 ++++ crates/io/src/psd_export/resources.rs | 116 +++ crates/io/src/psd_export/smart.rs | 253 ++++++ crates/io/src/psd_export/tests.rs | 12 +- 7 files changed, 1059 insertions(+), 1035 deletions(-) create mode 100644 crates/io/src/psd_export/document.rs create mode 100644 crates/io/src/psd_export/estimate.rs create mode 100644 crates/io/src/psd_export/merged.rs create mode 100644 crates/io/src/psd_export/resources.rs create mode 100644 crates/io/src/psd_export/smart.rs diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index af4739b661..0c809273a9 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -15,6 +15,23 @@ use crate::blocks; use crate::pixels::{deinterleave, encode_be, psd_depth}; use crate::psd_import::REGENERATED; +mod document; +mod estimate; +mod merged; +mod resources; +mod smart; + +pub(crate) use document::document_to_psd_interruptible; +pub use document::{document_to_psd, document_to_psd_with}; +use document::{document_to_psd_nested, mask_parameters}; +#[cfg(test)] +pub(crate) use estimate::estimate_psd_size; +pub(crate) use estimate::{block_signature, psd_size_exceeds_limit, psd_version}; +#[cfg(test)] +use estimate::{estimate_encoded_size, exceeds_psd_size_limit}; +pub(crate) use resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use smart::{LINK_KEYS, SmartOut, Source, contents_uuid, effects_unchanged, masked, size_from_layer, smart_keys, upsert}; + /// Blocks that define a layer's content as something other than pixels: fill (`SoCo`, `GdFl`, /// `PtFl`), placed / smart object (`SoLd`, `PlLd`, `SoLE`), type (`TySh`) and shape fill (`vscg`). /// A raster layer never writes them, nor adjustment blocks. @@ -138,202 +155,6 @@ fn psd_background(doc: &Document) -> Option { /// as pixels instead. const MAX_NESTING: u32 = 8; -/// An embedded smart-object source as written to `lnk2`. -#[derive(Clone, Debug)] -struct Source { - uuid: String, - /// Pixel size of the source document. - size: (f64, f64), - dpi: f64, -} - -fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { - let mut identity = blake3::Hasher::new(); - identity.update(&contents_id.0.to_le_bytes()); - identity.update(bytes); - crate::smart_map::uuid_from(identity.finalize().as_bytes()) -} - -/// Smart-object state collected while emitting layers, written into the global blocks at the end. -#[derive(Default)] -struct SmartOut { - /// Nesting depth of this export (embedded documents are exported recursively). - depth: u32, - /// The document's preserved global blocks (embedded files and filter caches from PSD import). - globals: Vec, - /// uuids of the files in the preserved linked-layer blocks. - known: std::collections::HashSet, - /// uuids the layers reference. - used: std::collections::HashSet, - /// Unreferenced preserved files may be dropped (every smart layer's file id is known). - prune_ok: bool, - /// Files to embed. - add: Vec, - /// Sources converted so far, by contents identity, bytes and whether they were read from a - /// link (`Err` = can't be embedded). - converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, - /// Each placed layer has its own id, even when it duplicates an imported layer. - placed_used: std::collections::HashSet, - /// Original instances reserve their imported placement regardless of layer order. - placed_owners: std::collections::HashMap, - /// Legacy records without a placed id stay unchanged for the original instance. - unplaced_owners: std::collections::HashMap, - /// The imported identity that keeps each original linked UUID. - linked_contents: std::collections::HashMap, - /// Independent copies of preserved linked items, including unavailable external sources. - linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, - /// Embedded documents decoded while converting them, by uuid (for the filter caches). - docs: std::collections::HashMap, - /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. - composites: std::collections::HashMap, photocraft_geom::Rect)>>, - /// Preserved `FEid` items (by placed id). - old_fx: Vec, - /// Placed ids whose preserved `FEid` item stays. - keep_fx: std::collections::HashSet, - /// Regenerated `FEid` items. - new_fx: Vec, - /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds - /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). - unfiltered: std::collections::HashMap, -} - -/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. -fn masked(sm: &photocraft_doc::SmartObject) -> bool { - sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) -} - -/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the -/// length and can't open a file whose `FEid` is padded outside it. -fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { - let mut d = fx.to_bytes(); - d.resize(d.len().next_multiple_of(4), 0); - d -} - -const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; -const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; - -impl SmartOut { - fn new(doc: &Document, depth: u32) -> Self { - let globals = doc.metadata.psd_global_blocks.clone(); - let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); - let old_fx = globals - .iter() - .filter(|(_, k, _)| FX_KEYS.contains(&k)) - .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) - .flat_map(|fx| fx.items) - .collect(); - let mut linked_contents = std::collections::HashMap::new(); - let mut placed_owners = std::collections::HashMap::new(); - let mut unplaced_owners = std::collections::HashMap::new(); - let mut layers = doc.walk(); - // Duplicating a layer clears psd_id and gives it a newer runtime id. - layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); - for (_, _, layer) in layers { - if let LayerContent::Smart(sm) = &layer.content - && let photocraft_doc::SmartSource::Linked { path } = &sm.source - && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) - && placed.idnt == *path - { - linked_contents.entry(path.clone()).or_insert(sm.contents_id); - if placed.placed.is_empty() { - unplaced_owners.entry(sm.contents_id).or_insert(layer.id); - } else { - placed_owners.entry(placed.placed).or_insert(layer.id); - } - } - } - SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } - } - - /// The document's global blocks with the linked-layer files and filter caches brought up to - /// date: unreferenced files dropped (when every reference is known), new files appended, - /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. - fn finish(&self, blocks: Vec) -> Vec { - use std::sync::Arc; - let keep = |u: &str| !self.prune_ok || self.used.contains(u); - let mut out = Vec::with_capacity(blocks.len() + 2); - let mut added = false; - let mut fx_placed = false; - for (sig, key, data) in blocks { - if LINK_KEYS.contains(&&key) { - let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; - added |= &key == b"lnk2"; - match crate::linked::rebuild_block(&data, &keep, add) { - None => out.push((sig, key, data)), - Some(d) if d.is_empty() => {} - Some(d) => out.push((sig, key, Arc::new(d))), - } - } else if FX_KEYS.contains(&&key) { - let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { - out.push((sig, key, data)); - continue; - }; - let before = fx.items.len(); - fx.items.retain(|i| self.keep_fx.contains(&i.id)); - let fresh = !fx_placed && !self.new_fx.is_empty(); - if fresh { - fx.items.extend(self.new_fx.iter().cloned()); - fx_placed = true; - } - if fx.items.len() == before && !fresh { - out.push((sig, key, data)); - } else if !fx.items.is_empty() { - out.push((sig, key, Arc::new(padded_fx(&fx)))); - } - } else { - out.push((sig, key, data)); - } - } - if !added && !self.add.is_empty() { - let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); - out.push((*b"8BIM", *b"lnk2", Arc::new(data))); - } - for (sig, key, data) in self.linked_copies.values() { - if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { - Arc::make_mut(block).extend_from_slice(data); - } else { - out.push((*sig, *key, data.clone())); - } - } - if !fx_placed && !self.new_fx.is_empty() { - let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; - out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); - if !out.iter().any(|(_, k, _)| k == b"FMsk") { - // Filter mask overlay: RGB red at 50 %, Photoshop's default. - out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); - } - } - out - } -} - -/// The source size of a smart object whose file we can't decode: its rendered bounds taken back -/// through the inverse transform (the source's top-left is the origin). -fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { - let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); - let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; - let [a, b, c, d, e, f] = inv.m; - let (mut w, mut h) = (1.0f64, 1.0f64); - for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { - let (x, y) = (f64::from(x), f64::from(y)); - w = w.max((a * x + c * y + e).round()); - h = h.max((b * x + d * y + f).round()); - } - (w, h) -} - -fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { - if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { - e.1 = data; - return; - } - match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { - Some(i) => raw.insert(i, (*key, data)), - None => raw.push((*key, data)), - } -} - fn h_of(r: photocraft_geom::Rect) -> usize { r.height() as usize } @@ -1195,836 +1016,5 @@ impl Ex { } } -/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order -/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). -/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise -/// groups are renumbered by first appearance. `None` when no layer is linked. -fn link_group_resource(layers: &[Layer]) -> Option> { - fn walk(layers: &[Layer], out: &mut Vec>) { - for l in layers { - if let LayerContent::Group(g) = &l.content { - out.push(None); - walk(&g.children, out); - } - out.push(l.link_group); - } - } - let mut per = Vec::new(); - walk(layers, &mut per); - if per.iter().all(Option::is_none) { - return None; - } - let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); - let mut seen: Vec = Vec::new(); - let ids = per.iter().map(|g| match *g { - None => 0u16, - Some(g) if fits => g as u16, - Some(g) => { - let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { - seen.push(g); - seen.len() - 1 - }); - u16::try_from(i + 1).unwrap_or(u16::MAX) - } - }); - Some(ids.flat_map(u16::to_be_bytes).collect()) -} - -/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` -/// decodes to. `None` when there is nothing preserved or it can't be decoded. -/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says -/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, -/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block -/// unreadable. -fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { - match data.and_then(|d| d.get(..4)) { - Some(b"plcL") => &[b"PlLd"], - Some(b"soLD") => &[b"SoLd", b"SoLE"], - _ => &[b"SoLd", b"PlLd", b"SoLE"], - } -} - -fn effects_unchanged(l: &Layer) -> Option { - let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; - let (m, items) = crate::effects_map::parse_lfx2(&src)?; - Some(m == l.effects.enabled && items == l.effects.items) -} - -pub(crate) fn legacy_name(s: &str) -> Vec { - s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() -} - -pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); - v.extend_from_slice(&(units.len() as u32).to_be_bytes()); - for u in units { - v.extend_from_slice(&u.to_be_bytes()); - } - } - v -} - -pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { - let mut v = Vec::new(); - for n in names { - let b = legacy_name(n); - let n = b.len().min(255); - v.push(n as u8); - v.extend_from_slice(&b[..n]); - } - // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes - // (length byte + 12 characters). The 8BIM container pads an odd resource separately. - v -} - -pub(crate) fn guides_resource(doc: &Document) -> Vec { - let mut v = Vec::new(); - v.extend_from_slice(&1u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - v.extend_from_slice(&576u32.to_be_bytes()); - let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); - v.extend_from_slice(&(n as u32).to_be_bytes()); - for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { - for p in list { - v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); - v.push(dir); - } - } - v -} - -/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), -/// the last only when the imported one doesn't already name the document's clipping path. -pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { - use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; - let mut out = Vec::new(); - let (w, h) = (doc.size.width, doc.size.height); - let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; - if doc.paths.len() > max { - warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); - } - for (i, p) in doc.paths.iter().take(max).enumerate() { - let data = match &p.psd_raw { - Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), - _ => path_to_records(&p.path, w, h).to_bytes(), - }; - let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); - r.name = legacy_name(&p.name); - out.push(r); - } - if let Some(wp) = &doc.work_path { - out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); - } - let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); - let raw_name = raw_clip.map(|(_, _, d)| { - let n = usize::from(d.first().copied().unwrap_or(0)); - d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() - }); - if let Some(c) = &doc.clipping_path - && raw_name.as_deref() != Some(c.name.as_str()) - { - // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). - let mut data = vec![0u8]; - let name = legacy_name(&c.name); - data[0] = name.len() as u8; - data.extend_from_slice(&name); - data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); - out.push(ImageResource::new(CLIPPING_PATH, data)); - } - out -} - -/// Whether an imported (unmodelled) resource still describes the document and is written back. -pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { - // Measurement scale / count resources: only while they still describe the document. - if !crate::annotations_map::keep_resource(doc, id) { - return false; - } - // Guides v2 and guide GUIDs: only while they still describe the document's guides. - if !crate::guides_map::keep_resource(doc, id, data) { - return false; - } - // A preserved clipping-path resource is only valid while it names the current one. - if id == crate::vector_map::CLIPPING_PATH { - let n = usize::from(data.first().copied().unwrap_or(0)); - let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); - return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); - } - true -} - -/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers -/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) -/// misaligned every block after it (#200). -pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { - let mut tb = TaggedBlock::new(key, data.to_vec()); - tb.signature = signature; - tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); - tb -} - -fn cmyk_of(fmt: &PixelFormat) -> bool { - fmt.mode == ColorMode::Cmyk -} - -/// The merged image's planes (colour channels, then alpha), big-endian, matted against white -/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. -/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the -/// image is left blank (the caller discards it). -fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { - if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { - return planes; - } - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * (cc + 1)]; - let (mut has_alpha, mut translucent) = (false, false); - let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let space = photocraft_compose::cmyk_space(doc); - let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; - let rows = canvas.height().max(1) as f32; - let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[3]) < 255, - SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[3] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[3] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - // Converted and encoded on all cores, then copied into each plane. - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - // The composite came through the document's CMYK profile: convert back through it too. - photocraft_color::convert::with_cmyk_space(space.as_ref(), || { - let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; - let mut v = [0.0f32; 5]; - for p in &band.px[range.clone()] { - photocraft_raster::from_rgba_into(fmt, *p, &mut v); - for c in 0..=cc { - // Matte against white like Photoshop (see `pixels::matte`). - let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; - let x = if cmyk && c < cc { 1.0 - m } else { m }; - // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - encode_be(x, sample, &mut out[c]); - } - } - (range.start, out) - }) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - planes[o..o + src.len()].copy_from_slice(src); - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - }); - (planes, has_alpha, translucent) -} - -/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values -/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents -/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. -fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { - let bps = sample.bytes(); - let n = doc.size.area() as usize; - let plane = n * bps; - let mut planes = vec![0u8; plane * 5]; - let (mut has_alpha, mut translucent) = (false, false); - let canvas = doc.bounds(); - let w = canvas.width() as usize; - let rows = canvas.height().max(1) as f32; - // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. - let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { - if ctl.cancelled() { - return Err(()); - } - // Retain alpha whenever it differs from opaque at the stored precision. - has_alpha |= band.px.iter().any(|p| match sample { - SampleType::U8 => q255(p[4]) < 255, - SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, - SampleType::F32 => p[4] != 1.0, - }); - translucent |= band.px.iter().any(|p| p[4] < 1.0); - let start = (band.rect.y0 - canvas.y0) as usize * w; - let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { - let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); - for p in band.px.get(range.clone()).unwrap_or(&[]) { - for (c, o) in out.iter_mut().enumerate() { - // Inks matted against white paper (no ink) like Photoshop (see - // `pixels::matte`), and stored inverted as PSD's CMYK is. - let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; - encode_be(v, sample, o); - } - } - (range.start, out) - }); - for (at, part) in parts { - for (c, src) in part.iter().enumerate() { - let o = c * plane + (start + at) * bps; - if let Some(dst) = planes.get_mut(o..o + src.len()) { - dst.copy_from_slice(src); - } - } - } - ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); - Ok(()) - })?; - Some((planes, has_alpha, translucent)) -} - -/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder -/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white -/// is no ink and Lab white is L 100 with neutral a*/b*. -fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { - let cc = fmt.mode.color_channels(); - let cmyk = cmyk_of(fmt); - let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; - let space = photocraft_compose::cmyk_space(doc); - let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); - let n = doc.size.area() as usize; - let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); - for c in 0..cc { - let v = white.get(c).copied().unwrap_or(1.0); - let x = if cmyk { 1.0 - v } else { v }; - let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; - let mut sample = Vec::with_capacity(4); - encode_be(x, fmt.sample, &mut sample); - planes.extend(sample.iter().copied().cycle().take(n * sample.len())); - } - planes -} - -/// Converts a document to a PSD file model (see [`document_to_psd_with`]). -pub fn document_to_psd(doc: &Document) -> PsdFile { - document_to_psd_with(doc, &PsdExportOptions::default()).0 -} - -/// Converts a document to a PSD/PSB file model, returning warnings about -/// anything that could not be represented. The merged composite is rendered -/// with `photocraft_compose::flatten`. -pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) -} - -/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after -/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops -/// early and returns an **incomplete** model: callers check `ctl` and discard it. -pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { - document_to_psd_nested(doc, opts, 0, ctl) -} - -/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it -/// (all layers composited) and encoding its planes cost about two full-canvas layers. -const MERGED_WEIGHT: f32 = 2.0; -/// The part of the merged composite's share filled once its bands are rendered and converted; the -/// rest is compressing its planes. -const MERGED_RENDERED: f32 = 0.8; - -/// Adds headroom for compressed channel streams and their per-row length tables. -fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { - raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) -} - -fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { - let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; - let plane_rows = height.checked_mul(channels)?; - *raw_bytes = raw_bytes.checked_add(plane_bytes)?; - *rows = rows.checked_add(plane_rows)?; - Some(()) -} - -fn exceeds_psd_size_limit(estimated_size: Option) -> bool { - estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) -} - -fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { - let bounds = surface.content_bounds(); - Some((u64::from(bounds.width()), u64::from(bounds.height()))) -} - -pub(crate) fn estimate_psd_size(doc: &Document) -> Option { - let mut raw_bytes = 0; - let mut rows = 0; - let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; - - let width = u64::from(doc.size.width); - let height = u64::from(doc.size.height); - - if doc.mode == ColorMode::Multichannel { - let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; - let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; - } else { - let format = doc.pixel_format(); - let color_channels = u64::try_from(format.mode.color_channels()).ok()?; - let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; - let layer_channels = color_channels.checked_add(1)?; - - for (_, _, layer) in doc.walk() { - structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; - for (_, data) in &layer.psd_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - let surface = match &layer.content { - LayerContent::Fill(fill) => { - let mut fill_width = width; - let mut fill_height = height; - if let Some(cache) = &layer.fill_cache - && cache.fill == *fill - { - let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; - fill_width = fill_width.max(cache_width); - fill_height = fill_height.max(cache_height); - } - add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; - None - } - _ => layer.surface(), - }; - if let Some(surface) = surface { - let (surface_width, surface_height) = surface_dimensions(surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; - } - if let Some(mask) = &layer.mask { - let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; - add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; - } - if let LayerContent::Smart(smart) = &layer.content - && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source - { - structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; - } - } - - let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); - let mut extra_channels = doc.channels.len().min(max_extra_channels); - if doc.quick_mask.is_some() && extra_channels < max_extra_channels { - extra_channels += 1; - } - let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; - add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; - for channel in doc.channels.iter().take(extra_channels) { - structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; - } - } - - structural_bytes = structural_bytes - .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? - .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? - .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; - for (_, name, data) in &doc.metadata.psd_resources { - structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; - } - for (_, _, data) in &doc.metadata.psd_global_blocks { - structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; - } - - estimate_encoded_size(raw_bytes, rows, structural_bytes) -} - -/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD -/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by -/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way -/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, -/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read -/// the length as 4 bytes and refuse the whole file (#7937). -pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { - match version { - Version::Psd if sig == *b"8B64" => *b"8BIM", - Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", - _ => sig, - } -} - -pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { - let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; - if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } -} - -pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { - exceeds_psd_size_limit(estimate_psd_size(doc)) -} - -/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. -fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { - if doc.mode == ColorMode::Multichannel { - return crate::multichannel_map::document_to_psd(doc, opts.force_psb); - } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { - return file; - } - let fmt = doc.pixel_format(); - // A Duotone is written over its grey plate with its inks: the block it was imported with, - // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop - // has only 8-bit Duotone: it refuses to open a 16-bit one. - let duotone_inks: Option> = doc - .duotone - .as_ref() - .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) - .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); - let sample = fmt.sample; - let cc = fmt.mode.color_channels(); - let big = doc.size.width > 30_000 || doc.size.height > 30_000; - let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); - let version = psd_version(doc, opts.force_psb, size_exceeds_limit); - let mut ex = Ex { - fmt, - dpi: doc.resolution_dpi, - document: opts.document_path.clone(), - read_linked_files: opts.read_linked_files, - text_styles: doc.text_styles.clone(), - text_index: Default::default(), - mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), - cc, - cmyk: fmt.mode == ColorMode::Cmyk, - version, - next_id: 0, - used_ids: Default::default(), - layer_ids: Default::default(), - canvas: doc.bounds(), - records: Vec::new(), - warnings: Vec::new(), - guides: doc.guides.clone(), - comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), - smart: SmartOut::new(doc, depth), - patterns: doc.patterns.clone(), - background: psd_background(doc), - }; - if big && !opts.force_psb { - ex.warnings.push("document exceeds 30000 px; written as PSB".into()); - } else if size_exceeds_limit && !opts.force_psb { - ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); - } - if fmt.mode != doc.mode && duotone_inks.is_none() { - ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); - } - // Assign layer ids up front (stable across round trips): keep unique - // `psd_id`s, number the rest after them; dividers come after all. - { - let walk = doc.walk(); - let mut used = std::collections::HashSet::new(); - for (_, _, l) in &walk { - if let Some(id) = l.psd_id - && used.insert(id) - { - ex.layer_ids.insert(l.id, id); - } - } - let mut next = 1u32; - for (_, _, l) in &walk { - if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { - while used.contains(&next) { - next += 1; - } - used.insert(next); - e.insert(next); - } - } - ex.next_id = used.iter().copied().max().unwrap_or(0); - ex.used_ids = used; - // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the - // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — - // and new layers get numbers past every kept one and every object in the file's `Txt2`. - // Kept numbers are claimed first: a layer added below others must not take a number a - // layer above it keeps, or each of those would be renumbered onto its neighbour's object - // and take its style (#7773); nor may it land on a deleted layer's object. - let mut used_txt = std::collections::HashSet::new(); - ex.text_index = Default::default(); - let mut fresh = Vec::new(); - for (_, _, l) in &walk { - let LayerContent::Text(t) = &l.content else { - continue; - }; - match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { - Some(i) if used_txt.insert(i) => { - ex.text_index.insert(l.id, i); - } - _ => fresh.push(l.id), - } - } - let objects = - doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); - let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); - if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { - next_txt = 0; - } - for id in fresh { - while used_txt.contains(&next_txt) { - next_txt += 1; - } - used_txt.insert(next_txt); - ex.text_index.insert(id, next_txt); - } - } - // Progress: one unit per layer record, then the merged composite (#3389). - let records = doc.walk().len() as f32; - let units = records + MERGED_WEIGHT; - let layers_share = records / units; - let mut done = 0.0f32; - let mut tick = || { - done += 1.0; - ctl.progress(done / units); - !ctl.cancelled() - }; - let space = photocraft_compose::cmyk_space(doc); - photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); - - // Without Maximize Compatibility the merged image is a white placeholder and the composite - // isn't rendered at all. A document without layer records keeps the real image: its pixels - // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records - // are not read back). - let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); - let (mut planes, has_alpha) = if real_merged { - // Merged composite, rendered and encoded in bands (no full-size float composite). Matting - // against white only changes pixels with alpha < 1; if some are slightly translucent but - // all round to opaque (so no alpha channel is written), encode once more without the matte. - let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; - let (mut planes, has_alpha, translucent) = - crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); - if !has_alpha && translucent && opts.merged_matte { - planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; - } - (planes, has_alpha) - } else { - (placeholder_planes(doc, &fmt), false) - }; - let n = doc.size.area() as usize; - if !has_alpha { - planes.truncate(cc * n * sample.bytes()); - } - let canvas = doc.bounds(); - let max_extra = 56 - cc - usize::from(has_alpha); - if doc.channels.len() > max_extra { - ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); - } - let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); - // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by - // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. - let quick_mask_id = match &doc.quick_mask { - Some(q) if extra.len() < max_extra => { - extra.push(q); - Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) - } - Some(_) => { - ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); - None - } - None => None, - }; - for a in &extra { - let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; - let mut bytes = s.to_interleaved(canvas); - // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. - if a.spot.is_some() { - crate::channel_map::photoshop_spot_plane(&mut bytes, sample); - } - planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); - } - let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; - let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; - let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); - let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; - let image_data = ImageData::encode(mcomp, &planes, &header) - .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) - .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); - ctl.progress(1.0); - - // Resources. - let mut resources = vec![ - // hRes/vRes are always pixels per inch. The display unit written here is inches. - ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), - ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), - ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), - ]; - if let Some(icc) = &doc.icc_profile { - resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); - } - if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { - resources.push(ImageResource::new(1032, guides_resource(doc))); - } - if !extra.is_empty() { - // One entry per extra channel, the merged transparency included (as in every file - // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). - let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); - resources.push(ImageResource::new(1006, pascal_names_resource(&names))); - resources.push(ImageResource::new(1045, unicode_names_resource(&names))); - resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); - // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from - // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). - resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); - } - if let Some(id) = quick_mask_id { - let mut data = id.to_be_bytes().to_vec(); - data.push(0); - resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); - } - resources.extend(path_resources(doc, &mut ex.warnings)); - if let Some(groups) = link_group_resource(&doc.layers) { - resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); - } - // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and - // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). - let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); - if let Some(x) = &doc.metadata.xmp { - resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); - } - if let Some(e) = &doc.metadata.exif { - resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); - } - let mut global_blocks = Vec::new(); - let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); - // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved - // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's - // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block - // it replaces is handed over so a kept object keeps everything the file held beyond its text - // and style runs (Photoshop's `/21 /1` glyph pen positions, …). - let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc - .walk() - .into_iter() - .filter_map(|(_, _, l)| match &l.content { - LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), - _ => None, - }) - .collect(); - let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); - // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never - // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the - // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the - // one mode EngineData can't carry; #1348). - let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) - .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); - for (sig, key, data) in preserved { - if txt2.is_some() && key == *b"Txt2" { - continue; - } - // A kept layer block (one the import could not read, #2700) describes layers the - // document doesn't have. The document's own layers are written below, and a file holds - // one layer list: a second `Lr16`/`Lr32` would contradict it. - if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { - continue; - } - let block = global_block(block_signature(sig, key, version), key, &data); - // A kept merged-transparency marker describes the opened file's composite. Over an opaque - // one it would make the first alpha channel read back as the transparency, and vanish. - if !has_alpha && block.is_merged_transparency_marker() { - continue; - } - global_blocks.push(block); - } - if let Some(txt2) = txt2 { - let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); - tb.signature = *b"8BIM"; - tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); - global_blocks.push(tb); - } - let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); - let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); - if let Some(warning) = slices_warning { - ex.warnings.push(warning); - } - for (id, name, data) in &doc.metadata.psd_resources { - // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. - if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { - continue; - } - // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. - if *id == crate::slices_map::SLICES && slices_resource.is_some() { - continue; - } - if !keep_imported_resource(doc, *id, data) { - continue; - } - // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or - // a document saved by an earlier version) would be a second one, or list channels that - // are gone. - if *id == crate::channel_map::ALPHA_IDENTIFIERS { - continue; - } - let mut r = ImageResource::new(*id, data.to_vec()); - r.name = legacy_name(name); - resources.push(r); - } - if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { - resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); - } - if let Some(Some(data)) = comps_resource { - resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); - } - if let Some(Some(data)) = slices_resource { - resources.push(ImageResource::new(crate::slices_map::SLICES, data)); - } - resources.push(version_info_resource(real_merged)); - - let has_layers = !ex.records.is_empty(); - // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) - // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer - // block goes right after the last kept marker, else first. - let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); - let placement = match (has_layers, sample) { - (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, - (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, - _ => LayerInfoPlacement::Section, - }; - let records = std::mem::take(&mut ex.records); - let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); - if let Some(info) = &mut layer_info { - // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global - // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. - // A global block's length is the exact data length and its padding to 4 follows the block: - // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). - if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { - info.padding = Some(Vec::new()); - } else if info.pad_to(version, 4).is_err() { - info.padding = None; - } - } - // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not - // open a 32-bit file without them (#291). - let color_mode_data = match duotone_inks { - Some(raw) => raw, - None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), - }; - let file = PsdFile { - header, - color_mode_data, - resources, - layer_info, - layer_info_placement: placement, - global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), - global_blocks, - layer_mask_trailing: Vec::new(), - image_data, - }; - (file, ex.warnings) -} - -/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when -/// every value is the default (density 1, feather 0). -fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { - let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); - let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); - let p = - MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; - let flags = u8::from(p.user_density.is_some()) - | u8::from(p.user_feather.is_some()) << 1 - | u8::from(p.vector_density.is_some()) << 2 - | u8::from(p.vector_feather.is_some()) << 3; - (flags != 0).then_some(MaskParameters { flags, ..p }) -} - #[cfg(test)] mod tests; diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs new file mode 100644 index 0000000000..0ad7188a58 --- /dev/null +++ b/crates/io/src/psd_export/document.rs @@ -0,0 +1,391 @@ +use super::estimate::{MERGED_RENDERED, MERGED_WEIGHT, block_signature, psd_size_exceeds_limit, psd_version}; +use super::merged::{cmyk_of, merged_planes, placeholder_planes}; +use super::resources::{global_block, guides_resource, keep_imported_resource, legacy_name, pascal_names_resource, path_resources, unicode_names_resource}; +use super::smart::{SmartOut, link_group_resource}; +use super::*; + +/// Converts a document to a PSD file model (see [`document_to_psd_with`]). +pub fn document_to_psd(doc: &Document) -> PsdFile { + document_to_psd_with(doc, &PsdExportOptions::default()).0 +} + +/// Converts a document to a PSD/PSB file model, returning warnings about +/// anything that could not be represented. The merged composite is rendered +/// with `photocraft_compose::flatten`. +pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, &Interrupt::NONE) +} + +/// [`document_to_psd_with`] for a background save (#3389): reports progress through `ctl` after +/// each layer record and each band of the merged composite. Once `ctl` is cancelled it stops +/// early and returns an **incomplete** model: callers check `ctl` and discard it. +pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> (PsdFile, Vec) { + document_to_psd_nested(doc, opts, 0, ctl) +} + +/// [`document_to_psd_with`] for a document embedded `depth` smart objects deep. +pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> (PsdFile, Vec) { + if doc.mode == ColorMode::Multichannel { + return crate::multichannel_map::document_to_psd(doc, opts.force_psb); + } + if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb) { + return file; + } + let fmt = doc.pixel_format(); + // A Duotone is written over its grey plate with its inks: the block it was imported with, + // verbatim, while the inks are unedited, else one made from them (`duotone_map`). Photoshop + // has only 8-bit Duotone: it refuses to open a 16-bit one. + let duotone_inks: Option> = doc + .duotone + .as_ref() + .filter(|d| !d.inks.is_empty() && doc.mode == ColorMode::Duotone && fmt.mode == ColorMode::Grayscale && fmt.sample == SampleType::U8) + .map(|d| d.psd_raw.as_deref().map_or_else(|| crate::duotone_map::write(d), <[u8]>::to_vec)); + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let big = doc.size.width > 30_000 || doc.size.height > 30_000; + let size_exceeds_limit = opts.size_limit_psb && !opts.force_psb && !big && psd_size_exceeds_limit(doc); + let version = psd_version(doc, opts.force_psb, size_exceeds_limit); + let mut ex = Ex { + fmt, + dpi: doc.resolution_dpi, + document: opts.document_path.clone(), + read_linked_files: opts.read_linked_files, + text_styles: doc.text_styles.clone(), + text_index: Default::default(), + mask_fmt: PixelFormat::new(ColorMode::Grayscale, sample, false), + cc, + cmyk: fmt.mode == ColorMode::Cmyk, + version, + next_id: 0, + used_ids: Default::default(), + layer_ids: Default::default(), + canvas: doc.bounds(), + records: Vec::new(), + warnings: Vec::new(), + guides: doc.guides.clone(), + comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())), + smart: SmartOut::new(doc, depth), + patterns: doc.patterns.clone(), + background: psd_background(doc), + }; + if big && !opts.force_psb { + ex.warnings.push("document exceeds 30000 px; written as PSB".into()); + } else if size_exceeds_limit && !opts.force_psb { + ex.warnings.push("estimated encoded size exceeds 2 GB; written as PSB".into()); + } + if fmt.mode != doc.mode && duotone_inks.is_none() { + ex.warnings.push(format!("{:?} document written as {:?}", doc.mode, fmt.mode)); + } + // Assign layer ids up front (stable across round trips): keep unique + // `psd_id`s, number the rest after them; dividers come after all. + { + let walk = doc.walk(); + let mut used = std::collections::HashSet::new(); + for (_, _, l) in &walk { + if let Some(id) = l.psd_id + && used.insert(id) + { + ex.layer_ids.insert(l.id, id); + } + } + let mut next = 1u32; + for (_, _, l) in &walk { + if let std::collections::hash_map::Entry::Vacant(e) = ex.layer_ids.entry(l.id) { + while used.contains(&next) { + next += 1; + } + used.insert(next); + e.insert(next); + } + } + ex.next_id = used.iter().copied().max().unwrap_or(0); + ex.used_ids = used; + // Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the + // number it already names — its `Txt2` object must sit at that slot for `apply_txt2` — + // and new layers get numbers past every kept one and every object in the file's `Txt2`. + // Kept numbers are claimed first: a layer added below others must not take a number a + // layer above it keeps, or each of those would be renumbered onto its neighbour's object + // and take its style (#7773); nor may it land on a deleted layer's object. + let mut used_txt = std::collections::HashSet::new(); + ex.text_index = Default::default(); + let mut fresh = Vec::new(); + for (_, _, l) in &walk { + let LayerContent::Text(t) = &l.content else { + continue; + }; + match t.psd_raw.as_deref().and_then(|d| photocraft_text::psd::text_index(d)) { + Some(i) if used_txt.insert(i) => { + ex.text_index.insert(l.id, i); + } + _ => fresh.push(l.id), + } + } + let objects = + doc.metadata.psd_global_blocks.iter().find(|(_, key, _)| key == b"Txt2").map_or(0, |(_, _, d)| photocraft_text::psd::txt2_object_count(d)); + let mut next_txt = used_txt.iter().max().map_or(0, |m| m + 1).max(i32::try_from(objects).unwrap_or(i32::MAX)); + if next_txt.saturating_add(fresh.len() as i32) > photocraft_text::psd::MAX_TEXT_INDEX + 1 { + next_txt = 0; + } + for id in fresh { + while used_txt.contains(&next_txt) { + next_txt += 1; + } + used_txt.insert(next_txt); + ex.text_index.insert(id, next_txt); + } + } + // Progress: one unit per layer record, then the merged composite (#3389). + let records = doc.walk().len() as f32; + let units = records + MERGED_WEIGHT; + let layers_share = records / units; + let mut done = 0.0f32; + let mut tick = || { + done += 1.0; + ctl.progress(done / units); + !ctl.cancelled() + }; + let space = photocraft_compose::cmyk_space(doc); + photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); + + // Without Maximize Compatibility the merged image is a white placeholder and the composite + // isn't rendered at all. A document without layer records keeps the real image: its pixels + // live nowhere else. So does a Duotone: it opens flattened from that image (its layer records + // are not read back). + let real_merged = opts.maximize_compatibility || ex.records.is_empty() || duotone_inks.is_some(); + let (mut planes, has_alpha) = if real_merged { + // Merged composite, rendered and encoded in bands (no full-size float composite). Matting + // against white only changes pixels with alpha < 1; if some are slightly translucent but + // all round to opaque (so no alpha channel is written), encode once more without the matte. + let merged_end = layers_share + (1.0 - layers_share) * MERGED_RENDERED; + let (mut planes, has_alpha, translucent) = + crate::with_span(ctl, layers_share, merged_end, |ctl| merged_planes(doc, &fmt, cmyk_of(&fmt), opts.merged_matte, ctl)); + if !has_alpha && translucent && opts.merged_matte { + planes = merged_planes(doc, &fmt, cmyk_of(&fmt), false, &Interrupt::cancel_only(&|| ctl.cancelled())).0; + } + (planes, has_alpha) + } else { + (placeholder_planes(doc, &fmt), false) + }; + let n = doc.size.area() as usize; + if !has_alpha { + planes.truncate(cc * n * sample.bytes()); + } + let canvas = doc.bounds(); + let max_extra = 56 - cc - usize::from(has_alpha); + if doc.channels.len() > max_extra { + ex.warnings.push(format!("only {max_extra} alpha channels fit in PSD; the rest were dropped")); + } + let mut extra: Vec<_> = doc.channels.iter().take(max_extra).collect(); + // Saved in Quick Mask mode: the mask is written as the last extra channel and flagged by + // resource 1022 (quick mask info: channel id, initially-empty flag), as Photoshop does. + let quick_mask_id = match &doc.quick_mask { + Some(q) if extra.len() < max_extra => { + extra.push(q); + Some((cc + usize::from(has_alpha) + extra.len() - 1) as u16) + } + Some(_) => { + ex.warnings.push("Quick Mask was dropped because the PSD channel limit was reached".into()); + None + } + None => None, + }; + for a in &extra { + let s = if a.surface.format() != ex.mask_fmt { a.surface.convert(ex.mask_fmt) } else { a.surface.clone() }; + let mut bytes = s.to_interleaved(canvas); + // Spot ink as Photoshop stores it (0 = solid); an alpha channel stays straight. + if a.spot.is_some() { + crate::channel_map::photoshop_spot_plane(&mut bytes, sample); + } + planes.extend(deinterleave(&bytes, 1, sample, &[false]).remove(0)); + } + let channels = (cc + usize::from(has_alpha) + extra.len()) as u16; + let mode = if duotone_inks.is_some() { PsdMode::Duotone } else { psd_mode(fmt.mode) }; + let header = Header::new(version, doc.size.width, doc.size.height, channels, psd_depth(sample), mode); + let mcomp = if sample == SampleType::F32 { Compression::Raw } else { opts.merged_compression }; + let image_data = ImageData::encode(mcomp, &planes, &header) + .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) + .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); + ctl.progress(1.0); + + // Resources. + let mut resources = vec![ + // hRes/vRes are always pixels per inch. The display unit written here is inches. + ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), + ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), + ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), + ]; + if let Some(icc) = &doc.icc_profile { + resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); + } + if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { + resources.push(ImageResource::new(1032, guides_resource(doc))); + } + if !extra.is_empty() { + // One entry per extra channel, the merged transparency included (as in every file + // Photoshop opens; one short, Photoshop refuses the file with "unexpected end-of-file"). + let names: Vec<&str> = has_alpha.then_some("Transparency").into_iter().chain(extra.iter().map(|a| a.name.as_str())).collect(); + resources.push(ImageResource::new(1006, pascal_names_resource(&names))); + resources.push(ImageResource::new(1045, unicode_names_resource(&names))); + resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(&extra, has_alpha))); + // Photoshop writes 1053 in every file with an extra channel. Its absence is how a file from + // an earlier PhotoCraft is told apart (`psd_import::earlier_photocraft_spot_planes`). + resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(has_alpha, extra.len()))); + } + if let Some(id) = quick_mask_id { + let mut data = id.to_be_bytes().to_vec(); + data.push(0); + resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); + } + resources.extend(path_resources(doc, &mut ex.warnings)); + if let Some(groups) = link_group_resource(&doc.layers) { + resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); + } + // The pixels are saved as they are shown: never let a reader rotate them again. The XMP and + // EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it (#1691). + let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); + if let Some(x) = &doc.metadata.xmp { + resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); + } + if let Some(e) = &doc.metadata.exif { + resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); + } + let mut global_blocks = Vec::new(); + let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc))); + // The type layers' `Txt2` is regenerated (the auto-kern modes live there, and a preserved + // block goes stale as text is edited): one object per `TextIndex`, at the slot each layer's + // `TySh` names (unused slots stay empty; see `photocraft_text::psd::build_txt2`). The block + // it replaces is handed over so a kept object keeps everything the file held beyond its text + // and style runs (Photoshop's `/21 /1` glyph pen positions, …). + let text_layers: Vec<(i32, &photocraft_doc::TextLayer)> = doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Text(t) => Some((ex.text_index.get(&l.id).copied().unwrap_or(0), t)), + _ => None, + }) + .collect(); + let previous = (!text_layers.is_empty()).then(|| preserved.iter().find(|(_, key, _)| key == b"Txt2").map(|(_, _, data)| data.to_vec())).flatten(); + // A fresh document of ordinary (Metrics) text has nothing to put in `Txt2`, and Photoshop never + // writes its empty `<< /0 << >> >>` stub — readers such as Photopea reject it (#3514). Keep the + // block when the file had one (round-trip its pen positions/extras) or a layer is Optical (the + // one mode EngineData can't carry; #1348). + let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)) + .then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi)); + for (sig, key, data) in preserved { + if txt2.is_some() && key == *b"Txt2" { + continue; + } + // A kept layer block (one the import could not read, #2700) describes layers the + // document doesn't have. The document's own layers are written below, and a file holds + // one layer list: a second `Lr16`/`Lr32` would contradict it. + if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + continue; + } + let block = global_block(block_signature(sig, key, version), key, &data); + // A kept merged-transparency marker describes the opened file's composite. Over an opaque + // one it would make the first alpha channel read back as the transparency, and vanish. + if !has_alpha && block.is_merged_transparency_marker() { + continue; + } + global_blocks.push(block); + } + if let Some(txt2) = txt2 { + let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); + tb.signature = *b"8BIM"; + tb.padding = Some(vec![0; (4 - txt2.len() % 4) % 4]); + global_blocks.push(tb); + } + let comps_resource = ex.comps.is_some().then(|| crate::comps_map::write_comps_resource(doc)); + let (slices_resource, slices_warning) = crate::slices_map::export_resource(doc, &ex.layer_ids); + if let Some(warning) = slices_warning { + ex.warnings.push(warning); + } + for (id, name, data) in &doc.metadata.psd_resources { + // Layer comps: the preserved list while unchanged, else regenerated (or dropped) below. + if *id == crate::comps_map::LAYER_COMPS && comps_resource.is_some() { + continue; + } + // Slices: the preserved resource while unchanged, else regenerated (or dropped) below. + if *id == crate::slices_map::SLICES && slices_resource.is_some() { + continue; + } + if !keep_imported_resource(doc, *id, data) { + continue; + } + // 1053 is written afresh with the extra channels. A kept copy (from a Multichannel file, or + // a document saved by an earlier version) would be a second one, or list channels that + // are gone. + if *id == crate::channel_map::ALPHA_IDENTIFIERS { + continue; + } + let mut r = ImageResource::new(*id, data.to_vec()); + r.name = legacy_name(name); + resources.push(r); + } + if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { + resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); + } + if let Some(Some(data)) = comps_resource { + resources.push(ImageResource::new(crate::comps_map::LAYER_COMPS, data)); + } + if let Some(Some(data)) = slices_resource { + resources.push(ImageResource::new(crate::slices_map::SLICES, data)); + } + resources.push(version_info_resource(real_merged)); + + let has_layers = !ex.records.is_empty(); + // Photoshop writes a merged-transparency marker (`Mtrn`, `Mt16`, `Mt32`; `MTrn` in a TIFF) + // before the layer block, and won't open a file whose `Lr32` comes first (#5068): the layer + // block goes right after the last kept marker, else first. + let index = global_blocks.iter().rposition(TaggedBlock::is_merged_transparency_marker).map_or(0, |i| i + 1); + let placement = match (has_layers, sample) { + (true, SampleType::U16) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr16", padding: None }, + (true, SampleType::F32) => LayerInfoPlacement::GlobalBlock { index, signature: *b"8BIM", key: *b"Lr32", padding: None }, + _ => LayerInfoPlacement::Section, + }; + let records = std::mem::take(&mut ex.records); + let mut layer_info = has_layers.then_some(LayerInfo { merged_alpha: has_alpha, layers: records, padding: None }); + if let Some(info) = &mut layer_info { + // Photoshop pads the layer info to 4 bytes (an even pad misaligns readers after a global + // `Lr16`/`Lr32` block, #200). A length that cannot be computed keeps the even default. + // A global block's length is the exact data length and its padding to 4 follows the block: + // readers that check that length exactly (Unity's PSD Importer) reject it otherwise (#4654). + if matches!(placement, LayerInfoPlacement::GlobalBlock { .. }) { + info.padding = Some(Vec::new()); + } else if info.pad_to(version, 4).is_err() { + info.padding = None; + } + } + // 32-bit files carry Photoshop's HDR toning records as Color Mode Data; Photoshop will not + // open a 32-bit file without them (#291). + let color_mode_data = match duotone_inks { + Some(raw) => raw, + None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), + }; + let file = PsdFile { + header, + color_mode_data, + resources, + layer_info, + layer_info_placement: placement, + global_layer_mask: (has_layers || !global_blocks.is_empty()).then(GlobalLayerMask::default), + global_blocks, + layer_mask_trailing: Vec::new(), + image_data, + }; + (file, ex.warnings) +} + +/// PSD mask parameters for a user mask's and a vector mask's (density, feather); `None` when +/// every value is the default (density 1, feather 0). +pub(super) fn mask_parameters(user: Option<(f32, f32)>, vector: Option<(f32, f32)>) -> Option { + let density = |v: Option<(f32, f32)>| v.and_then(|(d, _)| (d < 1.0).then(|| q255(d))); + let feather = |v: Option<(f32, f32)>| v.and_then(|(_, f)| (f.is_finite() && f > 0.0).then_some(f64::from(f))); + let p = + MaskParameters { flags: 0, user_density: density(user), user_feather: feather(user), vector_density: density(vector), vector_feather: feather(vector) }; + let flags = u8::from(p.user_density.is_some()) + | u8::from(p.user_feather.is_some()) << 1 + | u8::from(p.vector_density.is_some()) << 2 + | u8::from(p.vector_feather.is_some()) << 3; + (flags != 0).then_some(MaskParameters { flags, ..p }) +} diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs new file mode 100644 index 0000000000..83c2388a1e --- /dev/null +++ b/crates/io/src/psd_export/estimate.rs @@ -0,0 +1,135 @@ +use super::*; + +/// How much of a PSD conversion the merged composite weighs, in layer records: rendering it +/// (all layers composited) and encoding its planes cost about two full-canvas layers. +pub(super) const MERGED_WEIGHT: f32 = 2.0; + +/// The part of the merged composite's share filled once its bands are rendered and converted; the +/// rest is compressing its planes. +pub(super) const MERGED_RENDERED: f32 = 0.8; + +/// Adds headroom for compressed channel streams and their per-row length tables. +pub(super) fn estimate_encoded_size(raw_bytes: u64, rows: u64, structural_bytes: u64) -> Option { + raw_bytes.checked_add(raw_bytes.checked_add(63)?.checked_div(64)?)?.checked_add(rows.checked_mul(8)?)?.checked_add(structural_bytes) +} + +fn add_plane_estimate(raw_bytes: &mut u64, rows: &mut u64, width: u64, height: u64, channels: u64, bytes_per_sample: u64) -> Option<()> { + let plane_bytes = width.checked_mul(height)?.checked_mul(channels)?.checked_mul(bytes_per_sample)?; + let plane_rows = height.checked_mul(channels)?; + *raw_bytes = raw_bytes.checked_add(plane_bytes)?; + *rows = rows.checked_add(plane_rows)?; + Some(()) +} + +pub(super) fn exceeds_psd_size_limit(estimated_size: Option) -> bool { + estimated_size.is_none_or(|size| size > PSD_MAX_FILE_SIZE) +} + +fn surface_dimensions(surface: &Surface) -> Option<(u64, u64)> { + let bounds = surface.content_bounds(); + Some((u64::from(bounds.width()), u64::from(bounds.height()))) +} + +pub(crate) fn estimate_psd_size(doc: &Document) -> Option { + let mut raw_bytes = 0; + let mut rows = 0; + let mut structural_bytes = PSD_ESTIMATE_FIXED_OVERHEAD; + + let width = u64::from(doc.size.width); + let height = u64::from(doc.size.height); + + if doc.mode == ColorMode::Multichannel { + let channels = u64::try_from(doc.channels.len().clamp(1, 56)).ok()?; + let sample_bytes = u64::try_from(if doc.depth == SampleType::F32 { SampleType::U16.bytes() } else { doc.depth.bytes() }).ok()?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, channels, sample_bytes)?; + } else { + let format = doc.pixel_format(); + let color_channels = u64::try_from(format.mode.color_channels()).ok()?; + let bytes_per_sample = u64::try_from(format.sample.bytes()).ok()?; + let layer_channels = color_channels.checked_add(1)?; + + for (_, _, layer) in doc.walk() { + structural_bytes = structural_bytes.checked_add(PSD_ESTIMATE_LAYER_OVERHEAD)?.checked_add(u64::try_from(layer.name.len()).ok()?)?; + for (_, data) in &layer.psd_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + let surface = match &layer.content { + LayerContent::Fill(fill) => { + let mut fill_width = width; + let mut fill_height = height; + if let Some(cache) = &layer.fill_cache + && cache.fill == *fill + { + let (cache_width, cache_height) = surface_dimensions(&cache.surface)?; + fill_width = fill_width.max(cache_width); + fill_height = fill_height.max(cache_height); + } + add_plane_estimate(&mut raw_bytes, &mut rows, fill_width, fill_height, layer_channels, bytes_per_sample)?; + None + } + _ => layer.surface(), + }; + if let Some(surface) = surface { + let (surface_width, surface_height) = surface_dimensions(surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, surface_width, surface_height, layer_channels, bytes_per_sample)?; + } + if let Some(mask) = &layer.mask { + let (mask_width, mask_height) = surface_dimensions(&mask.surface)?; + add_plane_estimate(&mut raw_bytes, &mut rows, mask_width, mask_height, 1, bytes_per_sample)?; + } + if let LayerContent::Smart(smart) = &layer.content + && let photocraft_doc::SmartSource::Embedded { bytes, .. } = &smart.source + { + structural_bytes = structural_bytes.checked_add(u64::try_from(bytes.len()).ok()?)?; + } + } + + let max_extra_channels = 56usize.saturating_sub(format.mode.color_channels() + 1); + let mut extra_channels = doc.channels.len().min(max_extra_channels); + if doc.quick_mask.is_some() && extra_channels < max_extra_channels { + extra_channels += 1; + } + let merged_channels = color_channels.checked_add(1)?.checked_add(u64::try_from(extra_channels).ok()?)?; + add_plane_estimate(&mut raw_bytes, &mut rows, width, height, merged_channels, bytes_per_sample)?; + for channel in doc.channels.iter().take(extra_channels) { + structural_bytes = structural_bytes.checked_add(u64::try_from(channel.name.len()).ok()?)?; + } + } + + structural_bytes = structural_bytes + .checked_add(u64::try_from(doc.icc_profile.as_ref().map_or(0, |profile| profile.len())).ok()?)? + .checked_add(u64::try_from(doc.metadata.xmp.as_deref().map_or(0, str::len)).ok()?)? + .checked_add(u64::try_from(doc.metadata.exif.as_ref().map_or(0, |data| data.len())).ok()?)?; + for (_, name, data) in &doc.metadata.psd_resources { + structural_bytes = structural_bytes.checked_add(u64::try_from(name.len()).ok()?)?.checked_add(u64::try_from(data.len()).ok()?)?; + } + for (_, _, data) in &doc.metadata.psd_global_blocks { + structural_bytes = structural_bytes.checked_add(u64::try_from(data.len()).ok()?)?; + } + + estimate_encoded_size(raw_bytes, rows, structural_bytes) +} + +/// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD +/// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by +/// Photoshop as "not compatible with this version" (measured in Photoshop 27.11). The other way +/// round, a PSB block with an 8-byte length is `8B64`, as Photoshop writes it: an `8BIM` `lnk2`, +/// `pths` or `cinf` (kept from a PSD source, whose lengths the PSB widens) makes Photoshop read +/// the length as 4 bytes and refuse the whole file (#7937). +pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { + match version { + Version::Psd if sig == *b"8B64" => *b"8BIM", + Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", + _ => sig, + } +} + +pub(crate) fn psd_version(doc: &Document, force_psb: bool, size_exceeds_limit: bool) -> Version { + let exceeds_dimensions = doc.size.width > 30_000 || doc.size.height > 30_000; + if force_psb || exceeds_dimensions || size_exceeds_limit { Version::Psb } else { Version::Psd } +} + +pub(crate) fn psd_size_exceeds_limit(doc: &Document) -> bool { + exceeds_psd_size_limit(estimate_psd_size(doc)) +} diff --git a/crates/io/src/psd_export/merged.rs b/crates/io/src/psd_export/merged.rs new file mode 100644 index 0000000000..da3afe0597 --- /dev/null +++ b/crates/io/src/psd_export/merged.rs @@ -0,0 +1,143 @@ +use super::*; + +pub(super) fn cmyk_of(fmt: &PixelFormat) -> bool { + fmt.mode == ColorMode::Cmyk +} + +/// The merged image's planes (colour channels, then alpha), big-endian, matted against white +/// when `matte`; with whether any pixel needs the alpha channel and whether any is below 1. +/// `ctl` gets the fraction of rows done after each band; once it is cancelled the rest of the +/// image is left blank (the caller discards it). +pub(super) fn merged_planes(doc: &Document, fmt: &PixelFormat, cmyk: bool, matte: bool, ctl: &Interrupt) -> (Vec, bool, bool) { + if cmyk && let Some(planes) = merged_ink_planes(doc, fmt.sample, matte, ctl) { + return planes; + } + let sample = fmt.sample; + let cc = fmt.mode.color_channels(); + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * (cc + 1)]; + let (mut has_alpha, mut translucent) = (false, false); + let white = photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0]); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let space = photocraft_compose::cmyk_space(doc); + let lab16 = fmt.mode == ColorMode::Lab && sample == SampleType::U16; + let rows = canvas.height().max(1) as f32; + let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[3]) < 255, + SampleType::U16 => (p[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[3] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[3] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + // Converted and encoded on all cores, then copied into each plane. + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + // The composite came through the document's CMYK profile: convert back through it too. + photocraft_color::convert::with_cmyk_space(space.as_ref(), || { + let mut out: Vec> = vec![Vec::with_capacity(range.len() * bps); cc + 1]; + let mut v = [0.0f32; 5]; + for p in &band.px[range.clone()] { + photocraft_raster::from_rgba_into(fmt, *p, &mut v); + for c in 0..=cc { + // Matte against white like Photoshop (see `pixels::matte`). + let m = if c < cc && matte { crate::pixels::matte(v[c], v[cc], white[c]) } else { v[c] }; + let x = if cmyk && c < cc { 1.0 - m } else { m }; + // 16-bit Lab a*/b* use Photoshop's 0..65280 scale (`pixels::lab16_chroma`). + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + encode_be(x, sample, &mut out[c]); + } + } + (range.start, out) + }) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + planes[o..o + src.len()].copy_from_slice(src); + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + }); + (planes, has_alpha, translucent) +} + +/// [`merged_planes`] of a CMYK document whose layers are mixed on their ink values +/// (`photocraft_compose::cmyk`), so opaque pixels keep their exact inks; `None` for documents +/// that composite in RGB. Reports progress and stops on cancel like [`merged_planes`]. +fn merged_ink_planes(doc: &Document, sample: SampleType, matte: bool, ctl: &Interrupt) -> Option<(Vec, bool, bool)> { + let bps = sample.bytes(); + let n = doc.size.area() as usize; + let plane = n * bps; + let mut planes = vec![0u8; plane * 5]; + let (mut has_alpha, mut translucent) = (false, false); + let canvas = doc.bounds(); + let w = canvas.width() as usize; + let rows = canvas.height().max(1) as f32; + // A cancelled export leaves the rest blank (the caller discards it), so the result stands either way. + let _ = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> { + if ctl.cancelled() { + return Err(()); + } + // Retain alpha whenever it differs from opaque at the stored precision. + has_alpha |= band.px.iter().any(|p| match sample { + SampleType::U8 => q255(p[4]) < 255, + SampleType::U16 => (p[4].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 != u16::MAX, + SampleType::F32 => p[4] != 1.0, + }); + translucent |= band.px.iter().any(|p| p[4] < 1.0); + let start = (band.rect.y0 - canvas.y0) as usize * w; + let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| { + let mut out: Vec> = (0..5).map(|_| Vec::with_capacity(range.len() * bps)).collect(); + for p in band.px.get(range.clone()).unwrap_or(&[]) { + for (c, o) in out.iter_mut().enumerate() { + // Inks matted against white paper (no ink) like Photoshop (see + // `pixels::matte`), and stored inverted as PSD's CMYK is. + let v = if c < 4 { 1.0 - if matte { crate::pixels::matte(p[c], p[4], 0.0) } else { p[c] } } else { p[4] }; + encode_be(v, sample, o); + } + } + (range.start, out) + }); + for (at, part) in parts { + for (c, src) in part.iter().enumerate() { + let o = c * plane + (start + at) * bps; + if let Some(dst) = planes.get_mut(o..o + src.len()) { + dst.copy_from_slice(src); + } + } + } + ctl.progress((band.rect.y1 - canvas.y0) as f32 / rows); + Ok(()) + })?; + Some((planes, has_alpha, translucent)) +} + +/// The merged image of a file saved without Maximize Compatibility: Photoshop's white placeholder +/// in the document's colour channels, with no alpha. Encoded like [`merged_planes`], so CMYK white +/// is no ink and Lab white is L 100 with neutral a*/b*. +pub(super) fn placeholder_planes(doc: &Document, fmt: &PixelFormat) -> Vec { + let cc = fmt.mode.color_channels(); + let cmyk = cmyk_of(fmt); + let lab16 = fmt.mode == ColorMode::Lab && fmt.sample == SampleType::U16; + let space = photocraft_compose::cmyk_space(doc); + let white = photocraft_color::convert::with_cmyk_space(space.as_ref(), || photocraft_raster::from_rgba(fmt, [1.0, 1.0, 1.0, 1.0])); + let n = doc.size.area() as usize; + let mut planes = Vec::with_capacity(n * fmt.sample.bytes() * cc); + for c in 0..cc { + let v = white.get(c).copied().unwrap_or(1.0); + let x = if cmyk { 1.0 - v } else { v }; + let x = if lab16 && (c == 1 || c == 2) { x * (crate::pixels::LAB16_CHROMA_MAX / 65535.0) } else { x }; + let mut sample = Vec::with_capacity(4); + encode_be(x, fmt.sample, &mut sample); + planes.extend(sample.iter().copied().cycle().take(n * sample.len())); + } + planes +} diff --git a/crates/io/src/psd_export/resources.rs b/crates/io/src/psd_export/resources.rs new file mode 100644 index 0000000000..4ab5210e94 --- /dev/null +++ b/crates/io/src/psd_export/resources.rs @@ -0,0 +1,116 @@ +use super::*; + +pub(crate) fn legacy_name(s: &str) -> Vec { + s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() +} + +pub(crate) fn unicode_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let units: Vec = n.encode_utf16().chain(std::iter::once(0)).collect(); + v.extend_from_slice(&(units.len() as u32).to_be_bytes()); + for u in units { + v.extend_from_slice(&u.to_be_bytes()); + } + } + v +} + +pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { + let mut v = Vec::new(); + for n in names { + let b = legacy_name(n); + let n = b.len().min(255); + v.push(n as u8); + v.extend_from_slice(&b[..n]); + } + // No per-string pad: Photoshop's resource 1006 for "Spot Color 1" is 13 bytes + // (length byte + 12 characters). The 8BIM container pads an odd resource separately. + v +} + +pub(crate) fn guides_resource(doc: &Document) -> Vec { + let mut v = Vec::new(); + v.extend_from_slice(&1u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + v.extend_from_slice(&576u32.to_be_bytes()); + let n = doc.guides.horizontal.len() + doc.guides.vertical.len(); + v.extend_from_slice(&(n as u32).to_be_bytes()); + for (list, dir) in [(&doc.guides.vertical, 0u8), (&doc.guides.horizontal, 1u8)] { + for p in list { + v.extend_from_slice(&((p * 32.0).round() as i32).to_be_bytes()); + v.push(dir); + } + } + v +} + +/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), +/// the last only when the imported one doesn't already name the document's clipping path. +pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { + use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; + let mut out = Vec::new(); + let (w, h) = (doc.size.width, doc.size.height); + let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; + if doc.paths.len() > max { + warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); + } + for (i, p) in doc.paths.iter().take(max).enumerate() { + let data = match &p.psd_raw { + Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), + _ => path_to_records(&p.path, w, h).to_bytes(), + }; + let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); + r.name = legacy_name(&p.name); + out.push(r); + } + if let Some(wp) = &doc.work_path { + out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); + } + let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); + let raw_name = raw_clip.map(|(_, _, d)| { + let n = usize::from(d.first().copied().unwrap_or(0)); + d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() + }); + if let Some(c) = &doc.clipping_path + && raw_name.as_deref() != Some(c.name.as_str()) + { + // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). + let mut data = vec![0u8]; + let name = legacy_name(&c.name); + data[0] = name.len() as u8; + data.extend_from_slice(&name); + data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out.push(ImageResource::new(CLIPPING_PATH, data)); + } + out +} + +/// Whether an imported (unmodelled) resource still describes the document and is written back. +pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + // Measurement scale / count resources: only while they still describe the document. + if !crate::annotations_map::keep_resource(doc, id) { + return false; + } + // Guides v2 and guide GUIDs: only while they still describe the document's guides. + if !crate::guides_map::keep_resource(doc, id, data) { + return false; + } + // A preserved clipping-path resource is only valid while it names the current one. + if id == crate::vector_map::CLIPPING_PATH { + let n = usize::from(data.first().copied().unwrap_or(0)); + let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); + return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); + } + true +} + +/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers +/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) +/// misaligned every block after it (#200). +pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { + let mut tb = TaggedBlock::new(key, data.to_vec()); + tb.signature = signature; + tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); + tb +} diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs new file mode 100644 index 0000000000..264a2ab8ab --- /dev/null +++ b/crates/io/src/psd_export/smart.rs @@ -0,0 +1,253 @@ +use super::*; + +/// An embedded smart-object source as written to `lnk2`. +#[derive(Clone, Debug)] +pub(super) struct Source { + pub(super) uuid: String, + /// Pixel size of the source document. + pub(super) size: (f64, f64), + pub(super) dpi: f64, +} + +pub(super) fn contents_uuid(contents_id: SmartContentsId, bytes: &[u8]) -> String { + let mut identity = blake3::Hasher::new(); + identity.update(&contents_id.0.to_le_bytes()); + identity.update(bytes); + crate::smart_map::uuid_from(identity.finalize().as_bytes()) +} + +/// Smart-object state collected while emitting layers, written into the global blocks at the end. +#[derive(Default)] +pub(super) struct SmartOut { + /// Nesting depth of this export (embedded documents are exported recursively). + pub(super) depth: u32, + /// The document's preserved global blocks (embedded files and filter caches from PSD import). + pub(super) globals: Vec, + /// uuids of the files in the preserved linked-layer blocks. + pub(super) known: std::collections::HashSet, + /// uuids the layers reference. + pub(super) used: std::collections::HashSet, + /// Unreferenced preserved files may be dropped (every smart layer's file id is known). + pub(super) prune_ok: bool, + /// Files to embed. + pub(super) add: Vec, + /// Sources converted so far, by contents identity, bytes and whether they were read from a + /// link (`Err` = can't be embedded). + pub(super) converted: std::collections::HashMap<(SmartContentsId, [u8; 32], bool), Result>, + /// Each placed layer has its own id, even when it duplicates an imported layer. + pub(super) placed_used: std::collections::HashSet, + /// Original instances reserve their imported placement regardless of layer order. + pub(super) placed_owners: std::collections::HashMap, + /// Legacy records without a placed id stay unchanged for the original instance. + pub(super) unplaced_owners: std::collections::HashMap, + /// The imported identity that keeps each original linked UUID. + pub(super) linked_contents: std::collections::HashMap, + /// Independent copies of preserved linked items, including unavailable external sources. + pub(super) linked_copies: std::collections::BTreeMap<(String, SmartContentsId), photocraft_doc::PsdGlobalBlock>, + /// Embedded documents decoded while converting them, by uuid (for the filter caches). + pub(super) docs: std::collections::HashMap, + /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. + pub(super) composites: std::collections::HashMap, photocraft_geom::Rect)>>, + /// Preserved `FEid` items (by placed id). + pub(super) old_fx: Vec, + /// Placed ids whose preserved `FEid` item stays. + pub(super) keep_fx: std::collections::HashSet, + /// Regenerated `FEid` items. + pub(super) new_fx: Vec, + /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds + /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). + pub(super) unfiltered: std::collections::HashMap, +} + +/// Whether a smart object's filter mask shows: enabled over at least one visible, enabled filter. +pub(super) fn masked(sm: &photocraft_doc::SmartObject) -> bool { + sm.filter_mask.as_ref().is_some_and(|m| m.enabled) && sm.filters_enabled && sm.smart_filters.iter().any(|f| f.visible) +} + +/// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the +/// length and can't open a file whose `FEid` is padded outside it. +fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { + let mut d = fx.to_bytes(); + d.resize(d.len().next_multiple_of(4), 0); + d +} + +pub(super) const LINK_KEYS: [&[u8; 4]; 4] = [b"lnk2", b"lnk3", b"lnkD", b"lnkE"]; + +const FX_KEYS: [&[u8; 4]; 2] = [b"FEid", b"FXid"]; + +impl SmartOut { + pub(super) fn new(doc: &Document, depth: u32) -> Self { + let globals = doc.metadata.psd_global_blocks.clone(); + let known = globals.iter().filter(|(_, k, _)| LINK_KEYS.contains(&k)).flat_map(|(_, _, d)| crate::linked::block_uuids(d)).collect(); + let old_fx = globals + .iter() + .filter(|(_, k, _)| FX_KEYS.contains(&k)) + .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) + .flat_map(|fx| fx.items) + .collect(); + let mut linked_contents = std::collections::HashMap::new(); + let mut placed_owners = std::collections::HashMap::new(); + let mut unplaced_owners = std::collections::HashMap::new(); + let mut layers = doc.walk(); + // Duplicating a layer clears psd_id and gives it a newer runtime id. + layers.sort_by_key(|(_, _, layer)| (layer.psd_id.is_none(), layer.id)); + for (_, _, layer) in layers { + if let LayerContent::Smart(sm) = &layer.content + && let photocraft_doc::SmartSource::Linked { path } = &sm.source + && let Some(placed) = sm.psd_raw.as_ref().and_then(|d| crate::smart_map::parse_sold(d)) + && placed.idnt == *path + { + linked_contents.entry(path.clone()).or_insert(sm.contents_id); + if placed.placed.is_empty() { + unplaced_owners.entry(sm.contents_id).or_insert(layer.id); + } else { + placed_owners.entry(placed.placed).or_insert(layer.id); + } + } + } + SmartOut { depth, globals, known, prune_ok: true, old_fx, linked_contents, placed_owners, unplaced_owners, ..Default::default() } + } + + /// The document's global blocks with the linked-layer files and filter caches brought up to + /// date: unreferenced files dropped (when every reference is known), new files appended, + /// filter caches kept or regenerated per smart object. Unchanged blocks stay byte-identical. + pub(super) fn finish(&self, blocks: Vec) -> Vec { + use std::sync::Arc; + let keep = |u: &str| !self.prune_ok || self.used.contains(u); + let mut out = Vec::with_capacity(blocks.len() + 2); + let mut added = false; + let mut fx_placed = false; + for (sig, key, data) in blocks { + if LINK_KEYS.contains(&&key) { + let add: &[crate::linked::LinkedFile] = if !added && &key == b"lnk2" { &self.add } else { &[] }; + added |= &key == b"lnk2"; + match crate::linked::rebuild_block(&data, &keep, add) { + None => out.push((sig, key, data)), + Some(d) if d.is_empty() => {} + Some(d) => out.push((sig, key, Arc::new(d))), + } + } else if FX_KEYS.contains(&&key) { + let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { + out.push((sig, key, data)); + continue; + }; + let before = fx.items.len(); + fx.items.retain(|i| self.keep_fx.contains(&i.id)); + let fresh = !fx_placed && !self.new_fx.is_empty(); + if fresh { + fx.items.extend(self.new_fx.iter().cloned()); + fx_placed = true; + } + if fx.items.len() == before && !fresh { + out.push((sig, key, data)); + } else if !fx.items.is_empty() { + out.push((sig, key, Arc::new(padded_fx(&fx)))); + } + } else { + out.push((sig, key, data)); + } + } + if !added && !self.add.is_empty() { + let data: Vec = self.add.iter().flat_map(crate::linked::encode_linked_file).collect(); + out.push((*b"8BIM", *b"lnk2", Arc::new(data))); + } + for (sig, key, data) in self.linked_copies.values() { + if let Some((_, _, block)) = out.iter_mut().find(|(s, k, _)| s == sig && k == key) { + Arc::make_mut(block).extend_from_slice(data); + } else { + out.push((*sig, *key, data.clone())); + } + } + if !fx_placed && !self.new_fx.is_empty() { + let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; + out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); + if !out.iter().any(|(_, k, _)| k == b"FMsk") { + // Filter mask overlay: RGB red at 50 %, Photoshop's default. + out.push((*b"8BIM", *b"FMsk", Arc::new(vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]))); + } + } + out + } +} + +/// The source size of a smart object whose file we can't decode: its rendered bounds taken back +/// through the inverse transform (the source's top-left is the origin). +pub(super) fn size_from_layer(sm: &photocraft_doc::SmartObject) -> (f64, f64) { + let r = sm.cache.as_ref().map(Surface::content_bounds).filter(|r| !r.is_empty()); + let (Some(r), Some(inv)) = (r, sm.transform.inverse()) else { return (1.0, 1.0) }; + let [a, b, c, d, e, f] = inv.m; + let (mut w, mut h) = (1.0f64, 1.0f64); + for (x, y) in [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)] { + let (x, y) = (f64::from(x), f64::from(y)); + w = w.max((a * x + c * y + e).round()); + h = h.max((b * x + d * y + f).round()); + } + (w, h) +} + +pub(super) fn upsert(raw: &mut Vec<([u8; 4], Vec)>, key: &[u8; 4], data: Vec, before: Option<&[u8; 4]>) { + if let Some(e) = raw.iter_mut().find(|(k, _)| k == key) { + e.1 = data; + return; + } + match before.and_then(|b| raw.iter().position(|(k, _)| k == b)) { + Some(i) => raw.insert(i, (*key, data)), + None => raw.push((*key, data)), + } +} + +/// Resource 1026 (Layer › Link Layers): one u16 group id per layer record, in the order +/// [`Ex::emit`] writes records (a group's bounding divider, its children, then the group). +/// Imported ids that fit in a u16 are kept, so unchanged files write the same bytes; otherwise +/// groups are renumbered by first appearance. `None` when no layer is linked. +pub(super) fn link_group_resource(layers: &[Layer]) -> Option> { + fn walk(layers: &[Layer], out: &mut Vec>) { + for l in layers { + if let LayerContent::Group(g) = &l.content { + out.push(None); + walk(&g.children, out); + } + out.push(l.link_group); + } + } + let mut per = Vec::new(); + walk(layers, &mut per); + if per.iter().all(Option::is_none) { + return None; + } + let fits = per.iter().flatten().all(|&g| (1..=u64::from(u16::MAX)).contains(&g)); + let mut seen: Vec = Vec::new(); + let ids = per.iter().map(|g| match *g { + None => 0u16, + Some(g) if fits => g as u16, + Some(g) => { + let i = seen.iter().position(|&s| s == g).unwrap_or_else(|| { + seen.push(g); + seen.len() - 1 + }); + u16::try_from(i + 1).unwrap_or(u16::MAX) + } + }); + Some(ids.flat_map(u16::to_be_bytes).collect()) +} + +/// Whether the layer's effects still equal what its preserved `lmfx`/`lfx2` +/// decodes to. `None` when there is nothing preserved or it can't be decoded. +/// Block keys a smart object's `psd_raw` may be written under, in priority order. The data says +/// which it is: `PlLd` holds a `plcL` structure, `SoLd`/`SoLE` a `soLD` one (Adobe PSD spec, +/// "Placed Layer" and "Placed Layer Data"). Writing one under the other's key makes the block +/// unreadable. +pub(super) fn smart_keys(data: Option<&[u8]>) -> &'static [&'static [u8; 4]] { + match data.and_then(|d| d.get(..4)) { + Some(b"plcL") => &[b"PlLd"], + Some(b"soLD") => &[b"SoLd", b"SoLE"], + _ => &[b"SoLd", b"PlLd", b"SoLE"], + } +} + +pub(super) fn effects_unchanged(l: &Layer) -> Option { + let src = l.psd_blocks.iter().find(|(k, _)| k == b"lmfx").map(|(_, d)| d.clone()).or_else(|| l.effects.psd_raw.clone())?; + let (m, items) = crate::effects_map::parse_lfx2(&src)?; + Some(m == l.effects.enabled && items == l.effects.items) +} diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 5633e30764..9688dfeac2 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -245,8 +245,7 @@ fn photo_filter_psd_is_four_byte_aligned_and_round_trips() { let assert_phfl = |file: &PsdFile| { let records = &file.layer_info.as_ref().unwrap().layers; - let data = - records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); + let data = records.iter().flat_map(|r| r.blocks.iter()).find(|b| b.key == *b"phfl").map(|b| b.data.as_slice()).expect("Photo Filter adjustment data"); assert_eq!(data.len(), 20, "PSD layer block length includes four-byte padding"); assert_eq!(&data[0..2], &[0, 2], "version 2 RGB Photo Filter"); assert_eq!(&data[17..], &[0, 0, 0], "three padding bytes after the 17-byte payload"); @@ -279,8 +278,7 @@ fn photo_filter_version_3_is_kept_until_edited() { let v3 = vec![0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0]; let adjustment = crate::adjust_map::parse(b"phfl", &v3, None, crate::adjust_map::Channels::Rgb); let photocraft_doc::Adjustment::PhotoFilter { color, .. } = adjustment else { panic!("{adjustment:?}") }; - let mut doc = - Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); + let mut doc = Document::with_background("Photo Filter v3", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8, photocraft_doc::Color::WHITE); let mut layer = Layer::new("Photo Filter 1", LayerContent::Adjustment(adjustment.clone())); layer.psd_blocks = vec![(*b"phfl", std::sync::Arc::new(v3.clone()))]; doc.layers.push(layer); @@ -371,10 +369,8 @@ fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { // Photoshop 27.11 refuses a PSD holding `8B64` blocks ("not compatible with this // version"); they came from re-saving a PSB as PSD with its global FMsk and cinf kept. let mut doc = document(4, 4); - doc.metadata.psd_global_blocks = vec![ - (*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), - (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new())), - ]; + doc.metadata.psd_global_blocks = + vec![(*b"8B64", *b"FMsk", std::sync::Arc::new(vec![0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50])), (*b"8BIM", *b"Patt", std::sync::Arc::new(Vec::new()))]; let signatures = |force_psb| { let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap();