diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index dfc7e46c9ee..b5e9db31e11 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -79,6 +79,32 @@ struct Ex { smart: SmartOut, /// The document's patterns, which Pattern Fill layers are rendered from. patterns: Vec, + /// The layer written as Photoshop's Background (see [`psd_background`]). + background: Option, +} + +/// The layer Photoshop should open as its Background: the bottom top-level layer when it is a +/// locked (transparency and position), unclipped, unmasked raster that is opaque over the whole +/// canvas at full opacity and Normal, as a Background always is. Photoshop recognises a +/// Background by the bottom layer having no transparency channel (measured on Photoshop 27.11: +/// with the `-1` channel written, 317 of 427 re-exported corpus files reopened with the +/// Background as an ordinary layer). +fn psd_background(doc: &Document) -> Option { + let l = doc.layers.first()?; + let LayerContent::Raster(s) = &l.content else { return None }; + let locked = l.locks.transparency && l.locks.position; + let plain = !l.clipped && l.mask.is_none() && l.vector_mask.is_none() && l.opacity >= 1.0 && l.fill_opacity >= 1.0; + let normal = l.blend == photocraft_doc::BlendMode::Normal; + if !(locked && plain && normal) { + return None; + } + let canvas = doc.bounds(); + if canvas.is_empty() || s.content_bounds() != canvas { + return None; + } + let n = s.channels(); + let opaque = s.read_region(canvas).chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0)); + opaque.then_some(l.id) } /// How deep embedded documents are exported inside each other before a smart object is written @@ -407,7 +433,16 @@ impl Ex { real_first: true, }); } - let mut flags = LayerFlags(0); + // A Background carries no transparency channel: that is how Photoshop tells it apart. + if self.background == Some(l.id) { + channels.retain(|c| c.id != -1); + } + // As Photoshop writes them: bit 4 is meaningful, and set for layers whose pixels don't + // show (adjustment layers). + let mut flags = LayerFlags(LayerFlags::BIT4_USEFUL); + if matches!(l.content, LayerContent::Adjustment(_)) { + flags.0 |= LayerFlags::PIXEL_DATA_IRRELEVANT; + } flags.set_hidden(!l.visible); flags.set_transparency_protected(l.locks.transparency); let mut blocks = vec![TaggedBlock::unicode_name(&l.name), TaggedBlock::layer_id(id)]; @@ -1459,6 +1494,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c 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()); @@ -1751,6 +1787,47 @@ mod tests { Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8) } + /// Photoshop opens a PSD's bottom layer as its Background only when that layer has no + /// transparency channel (measured on Photoshop 27.11: with the channel written, re-exported + /// files reopened with the Background as an ordinary layer). + #[test] + fn a_background_is_written_without_a_transparency_channel() { + use photocraft_color::Color; + let size = photocraft_geom::Size::new(8, 6); + let mut doc = Document::with_background("bg", size, ColorMode::Rgb, SampleType::U8, Color::rgb(0.2, 0.4, 0.6)); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + let file = document_to_psd(&doc); + let layers = &file.layer_info.as_ref().unwrap().layers; + let ids = |i: usize| layers[i].channels.iter().map(|c| c.id).collect::>(); + assert_eq!(ids(0), vec![0, 1, 2], "the Background has no -1 channel"); + assert_eq!(layers[0].flags.0, LayerFlags::BIT4_USEFUL | LayerFlags::TRANSPARENCY_PROTECTED, "as Photoshop writes it"); + assert!(ids(1).contains(&-1), "other layers keep their transparency"); + // It comes back as the same locked, opaque Background. + let back = crate::import("bg.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &back.layers[0]; + assert!(bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + assert_eq!(bg.surface().unwrap().read_region(back.bounds()), doc.layers[0].surface().unwrap().read_region(doc.bounds())); + // A bottom layer with transparency (or unlocked) is not a Background. + let mut holey = doc.clone(); + holey.layers[0].surface_mut().unwrap().write_pixel(2, 2, &[0.0, 0.0, 0.0, 0.0]); + assert!(document_to_psd(&holey).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); + let mut unlocked = doc.clone(); + unlocked.layers[0].locks.position = false; + assert!(document_to_psd(&unlocked).layer_info.unwrap().layers[0].channels.iter().any(|c| c.id == -1)); + } + + /// A flat 1-bit Bitmap file (no layers) opens in Photoshop as its Background; so does it in + /// PhotoCraft, and it is written back as one (no transparency channel). + #[test] + fn a_flat_bitmap_file_opens_and_saves_as_a_background() { + let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); + let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; + let bg = &doc.layers[0]; + assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); + let out = document_to_psd(&doc); + assert!(out.layer_info.unwrap().layers[0].channels.iter().all(|c| c.id >= 0)); + } + #[test] fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() { let mut doc = document(8, 8); diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 1e77cdaa6a3..323fe600b3d 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -599,6 +599,35 @@ fn parse_guides(data: &[u8], doc: &mut Document) { } /// Converts a parsed PSD into a document. Never fails: problems become warnings. +/// A flattened file's merged image as its layer: like Photoshop, an opaque one is the locked +/// Background (Photoshop 27.11 opens psd-tools' flat Bitmap and Indexed files that way), so it is +/// written back as one. +fn flat_background(s: Surface) -> Layer { + let opaque = { + let r = s.content_bounds(); + let n = s.channels(); + !r.is_empty() && s.read_region(r).chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0)) + }; + let mut l = Layer::new("Background", LayerContent::Raster(s)); + l.locks.transparency = opaque; + l.locks.position = opaque; + l +} + +/// Photoshop opens a file's bottom layer as its Background when that layer's record has no +/// transparency (`-1`) channel, whatever its name and lock flags say: it is then locked and shown +/// as "Background" (measured on Photoshop 27.11 with files from psd-tools and ag-psd whose bottom +/// layer is called "Фон", "bg" or "Layer 1" and carries no locks). +fn mark_background(file: &PsdFile, layers: &mut [Layer]) { + let Some(rec) = file.layers().first() else { return }; + let Some(bottom) = layers.first_mut() else { return }; + let opaque_record = !rec.channels.is_empty() && rec.channels.iter().all(|c| c.id >= 0); + if opaque_record && matches!(bottom.content, LayerContent::Raster(_)) && !bottom.clipped { + bottom.locks.transparency = true; + bottom.locks.position = true; + } +} + pub fn psd_to_document(file: &PsdFile) -> (Document, Vec) { // Never cancelled, so always `Some`; the fallback is unreachable. psd_to_document_with(file, &photocraft_raster::Interrupt::NONE) @@ -759,16 +788,10 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt) // its own profile, as the compositor and the PSD writer read them. let space = photocraft_compose::cmyk_space(&doc); doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); - // Photoshop's Background: the bottom record, a transparency-protected pixel layer stored - // without a transparency channel (-1). It is also position-locked, whatever its - // (localized) name and whether or not the file carries an `lspf` block. - if let (Some(rec), Some(bottom)) = (file.layers().first(), doc.layers.first_mut()) - && rec.flags.transparency_protected() - && !rec.channels.iter().any(|c| c.id == -1) - && matches!(bottom.content, LayerContent::Raster(_)) - { - bottom.locks.position = true; - } + // Photoshop's Background: the bottom record stored without a transparency channel (-1), + // locked whatever its (localized) name and whether or not the file carries an `lspf` + // block. Its name is kept. + mark_background(file, &mut doc.layers); // Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked). if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) @@ -865,7 +888,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt) .collect(); s.write_region(canvas, &vals); s.prune(); - doc.layers.push(Layer::new("Background", LayerContent::Raster(s))); + doc.layers.push(flat_background(s)); } }