PhotoCraft: An open-source, photo editor written by scratch in pure Rust
PSD: rasterized fill and smart layers stay rasterized after save and reopen (#4034)
Brandon Thomas0d6e658e73d8
diff --git a/README.md b/README.mdindex 0455744b0..b6e8c5a60 100644--- a/README.md+++ b/README.md@@ -331,8 +331,6 @@ sha256-verified. Fetch them with `cargo xtask corpus --all` and run the tests wi| arm64 (Snapdragon and other ARM PCs) | `photocraft-<ver>-windows-arm64.msi` | `photocraft-<ver>-windows-arm64-portable.zip` || x86 (32-bit) | `photocraft-<ver>-windows-x86.msi` | `photocraft-<ver>-windows-x86-portable.zip` |-Windows 10 or later is required. On Windows 7 and 8 the app can't start (the installer says so).-Installers and executables are code-signed.### macOSdiff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rsindex f25ea9a2e..84c0e24de 100644--- a/crates/engine/src/extra_cmds.rs+++ b/crates/engine/src/extra_cmds.rs@@ -673,6 +673,9 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &strlet l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;l.content = LayerContent::Raster(px);l.fill_cache = None;+ // The PSD fill or placed-layer blocks no longer describe the layer: kept, they+ // would reopen it as a fill layer or smart object and drop these pixels.+ l.psd_blocks.retain(|(k, _)| !matches!(k, b"SoCo" | b"GdFl" | b"PtFl" | b"SoLd" | b"PlLd" | b"SoLE"));Ok(())});s.coalesce_request = None;diff --git a/crates/engine/tests/rasterize_psd_reopen.rs b/crates/engine/tests/rasterize_psd_reopen.rsnew file mode 100644index 000000000..a39005ac1--- /dev/null+++ b/crates/engine/tests/rasterize_psd_reopen.rs@@ -0,0 +1,115 @@+//! Layer › Rasterize › Fill Content / Smart Object stays rasterized after a PSD save and reopen.+//! A fill or smart layer opened from a PSD keeps its file blocks (`SoCo`/`GdFl`/`PtFl`,+//! `SoLd`/`PlLd`); left on the rasterized layer, they made the reopened file a fill layer or+//! smart object again and threw the pixels away. Photoshop writes none of them for a pixel layer.++use photocraft_doc::{Document, LayerContent, LayerId};+use photocraft_engine::Session;+use serde_json::{Value, json};++fn id_of(r: Value) -> LayerId {+ LayerId(r["layer"].as_u64().unwrap())+}++fn kind(l: &photocraft_doc::Layer) -> &'static str {+ match &l.content {+ LayerContent::Fill(_) => "fill",+ LayerContent::Smart(_) => "smart",+ LayerContent::Raster(_) => "raster",+ _ => "other",+ }+}++fn kind_named(doc: &Document, name: &str) -> &'static str {+ let l = doc.walk().into_iter().map(|(_, _, l)| l).find(|l| l.name == name).unwrap_or_else(|| panic!("no layer {name}"));+ kind(l)+}++fn reopen(doc: &Document) -> Document {+ let out = photocraft_io::export(doc, "psd", &Default::default()).unwrap();+ photocraft_io::import("x.psd", &out.bytes).unwrap().document+}++/// Whether the PSD written for `doc` gives the layer `name` any of `keys`.+fn has_block(doc: &Document, name: &str, keys: &[&[u8; 4]]) -> bool {+ let out = photocraft_io::export(doc, "psd", &Default::default()).unwrap();+ let f = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap();+ let rec = f.layers().iter().find(|r| r.name() == name).unwrap();+ keys.iter().any(|k| rec.block(k).is_some())+}++/// Rasterizes every layer named in `names` of a session opened on `doc`, then saves and reopens.+fn rasterize_and_reopen(doc: Document, names: &[&str]) -> Document {+ let mut s = Session::new();+ s.add_document(doc, None);+ for name in names {+ let id = s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l).find(|l| l.name == *name).unwrap().id;+ s.execute("layer.rasterize.layer", json!({"layer": id.0})).unwrap();+ assert_eq!(kind_named(&s.active().unwrap().doc, name), "raster");+ }+ reopen(&s.active().unwrap().doc)+}++#[test]+fn rasterized_fill_and_smart_object_reopen_as_pixels() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 48, "height": 32})).unwrap();+ s.execute("layer.new.layer", json!({"name": "Source"})).unwrap();+ s.execute("paint.stroke", json!({"points": [[20, 16]], "size": 12})).unwrap();+ let smart = id_of(s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap());+ let fill = id_of(s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap());+ let doc = s.active().unwrap().doc.clone();+ let smart_name = doc.layer(smart).unwrap().name.clone();+ let fill_name = doc.layer(fill).unwrap().name.clone();+ assert_ne!(smart_name, fill_name);++ // Opened from a PSD, both layers carry their file blocks.+ let opened = reopen(&doc);+ assert_eq!(kind_named(&opened, &fill_name), "fill");+ assert_eq!(kind_named(&opened, &smart_name), "smart");++ let back = rasterize_and_reopen(opened, &[&fill_name, &smart_name]);+ assert_eq!(kind_named(&back, &fill_name), "raster");+ assert_eq!(kind_named(&back, &smart_name), "raster");+ assert!(!has_block(&back, &fill_name, &[b"SoCo", b"GdFl", b"PtFl"]));+ assert!(!has_block(&back, &smart_name, &[b"SoLd", b"PlLd", b"SoLE"]));+}++/// The exporter never writes content-defining blocks for a pixel layer, whichever command made it+/// one (a backstop for paths that swap the content without pruning `psd_blocks`).+#[test]+fn raster_layer_with_stale_blocks_writes_none() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#ff0000"})).unwrap();+ let mut doc = reopen(&s.active().unwrap().doc);+ let (id, name) = doc.walk().into_iter().map(|(_, _, l)| l).find(|l| kind(l) == "fill").map(|l| (l.id, l.name.clone())).unwrap();+ let fmt = doc.pixel_format();+ let l = doc.layer_mut(id).unwrap();+ assert!(l.psd_blocks.iter().any(|(k, _)| k == b"SoCo"));+ l.content = LayerContent::Raster(photocraft_raster::Surface::new(fmt));+ l.psd_blocks.push((*b"TySh", std::sync::Arc::new(vec![0; 8])));+ l.psd_blocks.push((*b"vscg", std::sync::Arc::new(vec![0; 8])));+ l.psd_blocks.push((*b"levl", std::sync::Arc::new(vec![0; 8])));+ assert!(!has_block(&doc, &name, &[b"SoCo", b"TySh", b"vstk", b"vscg", b"SoLd", b"PlLd", b"levl"]));+ assert_eq!(kind_named(&reopen(&doc), &name), "raster");+}++/// The same through files Photoshop wrote: a gradient fill layer and a placed smart object.+#[cfg(feature = "corpus")]+#[test]+fn photoshop_fill_and_smart_layers_stay_rasterized() {+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");+ for (file, want) in [("psd-tools/gradient-fill.psd", "fill"), ("photoshop/smart-filters/sf-none-plain.psd", "smart")] {+ let path = root.join(file);+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --all`)", path.display()));+ let doc = photocraft_io::import(file, &bytes).unwrap().document;+ let names: Vec<String> = doc.walk().into_iter().map(|(_, _, l)| l).filter(|l| kind(l) == want).map(|l| l.name.clone()).collect();+ assert!(!names.is_empty(), "{file}: no {want} layer");+ let refs: Vec<&str> = names.iter().map(String::as_str).collect();+ let back = rasterize_and_reopen(doc, &refs);+ for n in &names {+ assert_eq!(kind_named(&back, n), "raster", "{file}: {n}");+ }+ }+}diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex e8784e111..1c43a3645 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -15,6 +15,11 @@ use crate::blocks;use crate::pixels::{deinterleave, encode_be, psd_depth};use crate::psd_import::REGENERATED;+/// 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.+const RASTER_STALE_KEYS: [&[u8; 4]; 8] = [b"SoCo", b"GdFl", b"PtFl", b"SoLd", b"PlLd", b"SoLE", b"TySh", b"vscg"];+const PSD_MAX_FILE_SIZE: u64 = 2 * 1024 * 1024 * 1024;const PSD_ESTIMATE_FIXED_OVERHEAD: u64 = 1024 * 1024;const PSD_ESTIMATE_LAYER_OVERHEAD: u64 = 64 * 1024;@@ -590,7 +595,16 @@ impl Ex {self.smart_blocks(l, sm, parsed, &mut raw);}}- LayerContent::Raster(_) | LayerContent::Group(_) => {}+ // A pixel layer carries no content-defining blocks: a fill, placed (smart), type or+ // shape-fill block left over from before Rasterize would make a reader (ours or+ // Photoshop's) reopen the layer as that kind and discard the pixels. A shape stroke+ // (`vstk`) beside a vector mask makes a shape too; without one, Photoshop keeps it on+ // pixel layers, so it stays. A vector mask (`vmsk`/`vsms`, `vogk`) stays.+ LayerContent::Raster(_) => {+ let masked = l.vector_mask.is_some();+ raw.retain(|(k, _)| !RASTER_STALE_KEYS.contains(&k) && !adjust_map::ADJUSTMENT_KEYS.contains(&k) && k != b"CgEd" && !(k == b"vstk" && masked));+ }+ LayerContent::Group(_) => {}}// Effects reference point: written from the field (in place, keeping block order).match l.effects.reference {diff --git a/packaging/windows/photocraft.en-us.wxl b/packaging/windows/photocraft.en-us.wxlindex 8c14594d1..faa2835ab 100644--- a/packaging/windows/photocraft.en-us.wxl+++ b/packaging/windows/photocraft.en-us.wxl@@ -7,6 +7,5 @@<String Id="WelcomeDlgTitle" Value="{\WixUI_Font_Bigger}Welcome to the [ProductName] [PhotocraftVersion] Setup Wizard" /><String Id="WelcomeDlgDescription" Value="The Setup Wizard will install [ProductName] version [PhotocraftVersion] on your computer. Click Next to continue or Cancel to exit the Setup Wizard." /><String Id="VerifyReadyDlgInstallTitle" Value="{\WixUI_Font_Title}Ready to install [ProductName] [PhotocraftVersion]" />- <String Id="RequiresWindows10" Value="PhotoCraft needs Windows 10 or later. This version of Windows can't run it." /><String Id="ExitDialogTitle" Value="{\WixUI_Font_Bigger}Completed the [ProductName] [PhotocraftVersion] Setup Wizard" /></WixLocalization>diff --git a/packaging/windows/photocraft.wxs b/packaging/windows/photocraft.wxsindex d0b490950..98dc1fdfd 100644--- a/packaging/windows/photocraft.wxs+++ b/packaging/windows/photocraft.wxs@@ -31,18 +31,6 @@DowngradeErrorMessage="A newer version of PhotoCraft is already installed." /><MediaTemplate EmbedCab="yes" CompressionLevel="high" />- <!-- Windows 10 or later. The Rust standard library has needed it since 1.78: on Windows 7 and- 8 the app fails at launch with "The procedure entry point ProcessPrng could not be located- in bcryptprimitives.dll" (#2310), so the installer says so instead of installing it.- `CurrentMajorVersionNumber` exists only from Windows 10 on, in the 32- and 64-bit- registry views alike; MSI's own VersionNT has reported both 603 and 1000 there.- `Installed` keeps repair and uninstall working on any Windows. -->- <Property Id="WINDOWS10ORLATER" Secure="yes">- <RegistrySearch Id="WindowsMajorVersion" Root="HKLM" Key="SOFTWARE\Microsoft\Windows NT\CurrentVersion"- Name="CurrentMajorVersionNumber" Type="raw" />- </Property>- <Launch Condition="Installed OR WINDOWS10ORLATER" Message="!(loc.RequiresWindows10)" />-<!-- MSI caches this icon using its Id as the filename. Advertised shortcuts to an.exe need an .exe icon identifier (ICE50), even when the source is an ICO. --><Icon Id="PhotocraftIcon.exe" SourceFile="$(var.IconPath)" />