From 739d5d0a7440d6d7b65f700e838c7a669067bdc5 Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Wed, 21 Oct 2026 23:12:15 -0400 Subject: [PATCH 01/22] Windows: start without prntvpt.dll; delay-load it for printing (#8272) craft-print's Windows backend sets printer options through winprint's Print Ticket calls (PTOpenProvider, PTGetPrintCapabilities, PTMergeAndValidatePrintTicket, PTConvertPrintTicketToDevMode), so photocraft.exe and photocraft-cli.exe imported prntvpt.dll at load time. Stripped Windows images without it refused to start, the same way they did for Windows.Data.Pdf.dll before #5884. Both apps now delay-load prntvpt.dll. file.print through the Windows spooler checks it loads (as well as Windows.Data.Pdf.dll) and reports an error instead of aborting; file.printers falls back to the GDI printer list without it. A new apps/photocraft test reads the built exe's PE import tables and asserts both DLLs are delay-loaded. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/build.rs | 10 ++- apps/photocraft/build.rs | 10 ++- apps/photocraft/tests/windows_delay_loads.rs | 82 ++++++++++++++++++++ crates/engine/src/print_cmds.rs | 52 ++++++++++--- crates/engine/src/print_cmds/tests.rs | 27 ++++--- 5 files changed, 150 insertions(+), 31 deletions(-) create mode 100644 apps/photocraft/tests/windows_delay_loads.rs diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index 3951c46b81..f911223974 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -12,12 +12,14 @@ fn main() -> std::io::Result<()> { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return Ok(()); } - // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which - // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe - // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; - // the print command checks for it first and reports an error instead. + // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, and its + // printer options (the Print Ticket API) import prntvpt.dll; stripped Windows images (NTLite, + // some N/LTSC builds) lack them. A load-time import stops the exe from starting at all + // ("windows.data.pdf.dll was not found", #5884; "prntvpt.dll", #8272), so load them on first + // use; the print commands check for them first and report an error instead. if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll"); + println!("cargo:rustc-link-arg-bins=/DELAYLOAD:prntvpt.dll"); println!("cargo:rustc-link-arg-bins=delayimp.lib"); } let mut res = winresource::WindowsResource::new(); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 48abc9f1a5..70a14b833e 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -11,12 +11,14 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, which - // stripped Windows images (NTLite, some N/LTSC builds) lack. A load-time import stops the exe - // from starting at all ("windows.data.pdf.dll was not found", #5884), so load it on first use; - // the print command checks for it first and reports an error instead. + // Printing to PDF (winprint's `PdfCreateRenderer`) imports Windows.Data.Pdf.dll, and its + // printer options (the Print Ticket API) import prntvpt.dll; stripped Windows images (NTLite, + // some N/LTSC builds) lack them. A load-time import stops the exe from starting at all + // ("windows.data.pdf.dll was not found", #5884; "prntvpt.dll", #8272), so load them on first + // use; the print commands check for them first and report an error instead. if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { println!("cargo:rustc-link-arg-bins=/DELAYLOAD:windows.data.pdf.dll"); + println!("cargo:rustc-link-arg-bins=/DELAYLOAD:prntvpt.dll"); println!("cargo:rustc-link-arg-bins=delayimp.lib"); } let mut res = winresource::WindowsResource::new(); diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs new file mode 100644 index 0000000000..737ddb5eb1 --- /dev/null +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -0,0 +1,82 @@ +//! Print-only Windows components must not be load-time imports of `photocraft.exe`: stripped +//! Windows images (NTLite, some N/LTSC builds) lack them, and a load-time import stops the app +//! from starting at all (#5884 Windows.Data.Pdf.dll, #8272 prntvpt.dll). `build.rs` delay-loads +//! them; this reads the built exe's PE import tables to prove it. +#![cfg(all(target_os = "windows", target_env = "msvc"))] + +/// Loaded on first use by the print commands, which check them first. +const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; + +#[test] +fn print_only_system_dlls_are_delay_loaded() { + let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); + let pe = Pe::parse(&exe); + let imports = pe.dll_names(1, 20, 12); + let delayed = pe.dll_names(13, 32, 4); + assert!(imports.iter().any(|d| d == "kernel32.dll"), "the import table parses: {imports:?}"); + for dll in PRINT_ONLY { + assert!(!imports.iter().any(|d| d == dll), "{dll} is a load-time import: {imports:?}"); + assert!(delayed.iter().any(|d| d == dll), "{dll} is not delay-loaded: {delayed:?}"); + } +} + +/// Just enough of a PE32+ image to list the DLLs its import directories name. +struct Pe<'a> { + bytes: &'a [u8], + /// Virtual address, virtual size, file offset of each section. + sections: Vec<(u32, u32, u32)>, + /// Offset of the optional header's data directories. + directories: usize, +} + +impl<'a> Pe<'a> { + fn parse(bytes: &'a [u8]) -> Self { + let pe = u32_at(bytes, 0x3c) as usize; + assert_eq!(&bytes[pe..pe + 4], b"PE\0\0"); + let coff = pe + 4; + let sections = u16_at(bytes, coff + 2) as usize; + let optional = coff + 20; + let optional_size = u16_at(bytes, coff + 16) as usize; + assert_eq!(u16_at(bytes, optional), 0x20b, "a PE32+ image"); + let table = optional + optional_size; + let sections = (0..sections) + .map(|i| { + let s = table + i * 40; + (u32_at(bytes, s + 12), u32_at(bytes, s + 8), u32_at(bytes, s + 20)) + }) + .collect(); + Pe { bytes, sections, directories: optional + 112 } + } + + fn offset(&self, rva: u32) -> usize { + let &(va, _, raw) = self.sections.iter().find(|&&(va, size, _)| rva >= va && rva < va + size).unwrap(); + (rva - va + raw) as usize + } + + /// The DLL names of data directory `index`: an array of `entry`-byte descriptors, ended by an + /// all-zero one, with the name's RVA at `name_at`. + fn dll_names(&self, index: usize, entry: usize, name_at: usize) -> Vec { + let rva = u32_at(self.bytes, self.directories + index * 8); + if rva == 0 { + return Vec::new(); + } + let start = self.offset(rva); + (0..) + .map(|i| start + i * entry) + .take_while(|&d| self.bytes[d..d + entry].iter().any(|&b| b != 0)) + .map(|d| { + let name = self.offset(u32_at(self.bytes, d + name_at)); + let end = name + self.bytes[name..].iter().position(|&b| b == 0).unwrap(); + String::from_utf8_lossy(&self.bytes[name..end]).to_ascii_lowercase() + }) + .collect() + } +} + +fn u16_at(b: &[u8], at: usize) -> u16 { + u16::from_le_bytes([b[at], b[at + 1]]) +} + +fn u32_at(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) +} diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9b264f0611..bebc12e624 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -193,9 +193,15 @@ fn cups_spool(job: &PrintJob) -> std::result::Result { fn system_printers(_s: &mut Session, p: &Value) -> Result { let named = p.get("printServer").and_then(Value::as_str).filter(|v| !v.is_empty()); if named.is_none() && system_spooler().is_some() { - let list = craft_print::printers(); - let default = list.iter().find(|p| p.default).map(|p| p.name.clone()); - let printers: Vec = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect(); + // craft-print asks each Windows driver about two-sided printing through prntvpt.dll; + // without it, list the spooler's printers through GDI instead (#8272). + let list: Vec<(String, bool)> = if require_print_tickets().is_ok() { + craft_print::printers().into_iter().map(|p| (p.name, p.default)).collect() + } else { + craft_print::rgb::printers().map_err(other)?.into_iter().map(|p| (p.name, p.default)).collect() + }; + let default = list.iter().find(|p| p.1).map(|p| p.0.clone()); + let printers: Vec = list.into_iter().map(|(name, default)| json!({"name": name, "default": default})).collect(); return Ok(json!({"server": Value::Null, "default": default, "printers": printers})); } #[cfg(all(not(target_arch = "wasm32"), not(target_os = "windows")))] @@ -646,31 +652,55 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spool ) } -/// Windows prints a PDF through Windows.Data.Pdf.dll, which the apps delay-load (see their -/// `build.rs`) so a Windows image without it still starts. Calling into it when it cannot load -/// would abort the process, so check that it loads first (#5884). +/// Windows prints a PDF through Windows.Data.Pdf.dll and sets its options through the Print +/// Ticket API in prntvpt.dll, which the apps delay-load (see their `build.rs`) so a Windows image +/// without them still starts. Calling into one that cannot load would abort the process, so check +/// that both load first (#5884, #8272). fn require_windows_pdf() -> Result<()> { #[cfg(target_os = "windows")] { - let root = std::env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from(r"C:\Windows")); - if !windows_pdf_loads(&windows_pdf_dll(std::path::Path::new(&root))) { + if !system_dll_loads(WINDOWS_PDF_DLL) { return Err(other( "printing this page needs the Windows PDF component (Windows.Data.Pdf.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.", )); } + require_print_tickets()?; + } + Ok(()) +} + +/// `craft-print` reads and sets Windows printer options through prntvpt.dll (the Print Ticket +/// API), which stripped Windows images can lack; the apps delay-load it (#8272). +fn require_print_tickets() -> Result<()> { + #[cfg(target_os = "windows")] + if !system_dll_loads(PRINT_TICKET_DLL) { + return Err(other( + "printing this page needs the Windows Print Ticket component (prntvpt.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.", + )); } Ok(()) } #[cfg(target_os = "windows")] -fn windows_pdf_dll(system_root: &std::path::Path) -> std::path::PathBuf { - system_root.join("System32").join("Windows.Data.Pdf.dll") +const WINDOWS_PDF_DLL: &str = "Windows.Data.Pdf.dll"; +#[cfg(target_os = "windows")] +const PRINT_TICKET_DLL: &str = "prntvpt.dll"; + +#[cfg(target_os = "windows")] +fn system_dll_loads(name: &str) -> bool { + let root = std::env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from(r"C:\Windows")); + dll_loads(&system_dll(std::path::Path::new(&root), name)) +} + +#[cfg(target_os = "windows")] +fn system_dll(system_root: &std::path::Path, name: &str) -> std::path::PathBuf { + system_root.join("System32").join(name) } /// Loads the DLL rather than checking the file exists: one that is present but cannot load (a /// dependency stripped too) would still abort at the delay-load stub. #[cfg(target_os = "windows")] -fn windows_pdf_loads(dll: &std::path::Path) -> bool { +fn dll_loads(dll: &std::path::Path) -> bool { dll.to_str().is_some_and(|p| winsafe::HINSTANCE::LoadLibrary(p).is_ok()) } diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 38567ffb6d..318d6c7187 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -848,24 +848,27 @@ mod cups { #[cfg(target_os = "windows")] #[test] -fn windows_pdf_component_is_detected_by_loading_its_dll() { - // #5884: a Windows image without a loadable Windows.Data.Pdf.dll reports an error instead of - // aborting at the delay-load stub. +fn windows_print_components_are_detected_by_loading_their_dlls() { + // #5884, #8272: a Windows image without a loadable Windows.Data.Pdf.dll or prntvpt.dll reports + // an error instead of aborting at the delay-load stub. let dir = tempfile::tempdir().unwrap(); - let dll = windows_pdf_dll(dir.path()); - assert!(!windows_pdf_loads(&dll)); - // Present but not loadable counts as missing. std::fs::create_dir(dir.path().join("System32")).unwrap(); - std::fs::write(&dll, b"MZ").unwrap(); - assert!(!windows_pdf_loads(&dll)); - let root = std::env::var_os("SystemRoot").unwrap(); - // The real DLL may be missing or unloadable on a stripped image; the check follows the loader. - let system = windows_pdf_dll(std::path::Path::new(&root)); - assert_eq!(require_windows_pdf().is_ok(), windows_pdf_loads(&system)); + for name in [WINDOWS_PDF_DLL, PRINT_TICKET_DLL] { + let dll = system_dll(dir.path(), name); + assert!(!dll_loads(&dll), "{name}: missing"); + // Present but not loadable counts as missing. + std::fs::write(&dll, b"MZ").unwrap(); + assert!(!dll_loads(&dll), "{name}: not loadable"); + } + // The real DLLs may be missing or unloadable on a stripped image; the checks follow the loader. + let tickets = system_dll_loads(PRINT_TICKET_DLL); + assert_eq!(require_print_tickets().is_ok(), tickets); + assert_eq!(require_windows_pdf().is_ok(), system_dll_loads(WINDOWS_PDF_DLL) && tickets); } #[cfg(not(target_os = "windows"))] #[test] fn the_windows_pdf_check_is_a_no_op_elsewhere() { assert!(require_windows_pdf().is_ok()); + assert!(require_print_tickets().is_ok()); } From 3286781a6d3aa4c578e2f8f11da0756dd94b9f43 Mon Sep 17 00:00:00 2001 From: Michael Higgins <55243596+Higgs32584@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:55:40 -0400 Subject: [PATCH 02/22] Update apps/photocraft/tests/windows_delay_loads.rs Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- apps/photocraft/tests/windows_delay_loads.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index 737ddb5eb1..4cf6572a44 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -2,7 +2,11 @@ //! Windows images (NTLite, some N/LTSC builds) lack them, and a load-time import stops the app //! from starting at all (#5884 Windows.Data.Pdf.dll, #8272 prntvpt.dll). `build.rs` delay-loads //! them; this reads the built exe's PE import tables to prove it. -#![cfg(all(target_os = "windows", target_env = "msvc"))] +#![cfg(all( + target_os = "windows", + target_env = "msvc", + target_pointer_width = "64", +))] /// Loaded on first use by the print commands, which check them first. const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; From d0a5971617637c21de7d88d44ebdca45b443929f Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Thu, 22 Oct 2026 19:09:41 -0400 Subject: [PATCH 03/22] fix cargo fmt --- apps/photocraft/tests/windows_delay_loads.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index 4cf6572a44..b047614dd1 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -2,11 +2,7 @@ //! Windows images (NTLite, some N/LTSC builds) lack them, and a load-time import stops the app //! from starting at all (#5884 Windows.Data.Pdf.dll, #8272 prntvpt.dll). `build.rs` delay-loads //! them; this reads the built exe's PE import tables to prove it. -#![cfg(all( - target_os = "windows", - target_env = "msvc", - target_pointer_width = "64", -))] +#![cfg(all(target_os = "windows", target_env = "msvc", target_pointer_width = "64",))] /// Loaded on first use by the print commands, which check them first. const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; From 1e00b7e91c7ef864deb457ea4cd4cffe7b079eee Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Tue, 3 Nov 2026 10:07:45 -0500 Subject: [PATCH 04/22] Check the print DLLs against a fixture Windows directory in the test The final assertions read the host SystemRoot, so they never exercised the temporary System32 the test builds. require_*_at take the root; the production wrappers pass the real one. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/print_cmds.rs | 38 ++++++++++++++++------- crates/engine/src/cmd/print_cmds/tests.rs | 25 +++++++++++---- 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index 56bad41ec6..3a63a770be 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -930,6 +930,8 @@ fn driver_printable(p: &Value) -> Option { Some(json!([pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3])) } +/// Lays out and renders the print page as a PDF for `cmd` and, when the params ask for it, sends +/// it to the printer through `spooler`; returns the job summary (paper, image rect, spooler). fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spooler>) -> Result { let fit = p.get("scaleToFit").and_then(Value::as_bool).unwrap_or(false); let driver = (fit && native_route(p, spooler)).then(|| with_driver_printable(p)); @@ -1012,14 +1014,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str, spooler: Option<&Spool /// that both load first (#5884, #8272). fn require_windows_pdf() -> Result<()> { #[cfg(target_os = "windows")] - { - if !system_dll_loads(WINDOWS_PDF_DLL) { - return Err(other( - "printing this page needs the Windows PDF component (Windows.Data.Pdf.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.", - )); - } - require_print_tickets()?; - } + require_windows_pdf_at(&system_root())?; Ok(()) } @@ -1027,7 +1022,25 @@ fn require_windows_pdf() -> Result<()> { /// API), which stripped Windows images can lack; the apps delay-load it (#8272). fn require_print_tickets() -> Result<()> { #[cfg(target_os = "windows")] - if !system_dll_loads(PRINT_TICKET_DLL) { + require_print_tickets_at(&system_root())?; + Ok(()) +} + +/// [`require_windows_pdf`] against the Windows directory `system_root` (tests pass a fixture). +#[cfg(target_os = "windows")] +fn require_windows_pdf_at(system_root: &std::path::Path) -> Result<()> { + if !dll_loads(&system_dll(system_root, WINDOWS_PDF_DLL)) { + return Err(other( + "printing this page needs the Windows PDF component (Windows.Data.Pdf.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.", + )); + } + require_print_tickets_at(system_root) +} + +/// [`require_print_tickets`] against the Windows directory `system_root` (tests pass a fixture). +#[cfg(target_os = "windows")] +fn require_print_tickets_at(system_root: &std::path::Path) -> Result<()> { + if !dll_loads(&system_dll(system_root, PRINT_TICKET_DLL)) { return Err(other( "printing this page needs the Windows Print Ticket component (prntvpt.dll), which is missing or cannot load. Save as PDF and print it from another app, or print an RGB image without page text or labels to print directly.", )); @@ -1040,12 +1053,13 @@ const WINDOWS_PDF_DLL: &str = "Windows.Data.Pdf.dll"; #[cfg(target_os = "windows")] const PRINT_TICKET_DLL: &str = "prntvpt.dll"; +/// The running Windows directory (`%SystemRoot%`), `C:\Windows` if the variable is unset. #[cfg(target_os = "windows")] -fn system_dll_loads(name: &str) -> bool { - let root = std::env::var_os("SystemRoot").unwrap_or_else(|| std::ffi::OsString::from(r"C:\Windows")); - dll_loads(&system_dll(std::path::Path::new(&root), name)) +fn system_root() -> std::path::PathBuf { + std::env::var_os("SystemRoot").map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from) } +/// Where the system DLL `name` lives under the Windows directory `system_root`. #[cfg(target_os = "windows")] fn system_dll(system_root: &std::path::Path, name: &str) -> std::path::PathBuf { system_root.join("System32").join(name) diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index 766215a10a..816815fc33 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -1183,11 +1183,13 @@ mod cups { } } +/// #5884, #8272: a Windows image without a loadable Windows.Data.Pdf.dll or prntvpt.dll reports +/// an error instead of aborting at the delay-load stub. The checks run against a fixture +/// `System32`, so they don't depend on what the host has installed. #[cfg(target_os = "windows")] #[test] fn windows_print_components_are_detected_by_loading_their_dlls() { - // #5884, #8272: a Windows image without a loadable Windows.Data.Pdf.dll or prntvpt.dll reports - // an error instead of aborting at the delay-load stub. + let system_dll_loads = |name| dll_loads(&system_dll(&system_root(), name)); let dir = tempfile::tempdir().unwrap(); std::fs::create_dir(dir.path().join("System32")).unwrap(); for name in [WINDOWS_PDF_DLL, PRINT_TICKET_DLL] { @@ -1197,12 +1199,23 @@ fn windows_print_components_are_detected_by_loading_their_dlls() { std::fs::write(&dll, b"MZ").unwrap(); assert!(!dll_loads(&dll), "{name}: not loadable"); } - // The real DLLs may be missing or unloadable on a stripped image; the checks follow the loader. - let tickets = system_dll_loads(PRINT_TICKET_DLL); - assert_eq!(require_print_tickets().is_ok(), tickets); - assert_eq!(require_windows_pdf().is_ok(), system_dll_loads(WINDOWS_PDF_DLL) && tickets); + // Both stubs fail to load, so both checks report the missing component. + assert!(require_print_tickets_at(dir.path()).is_err()); + assert!(require_windows_pdf_at(dir.path()).is_err()); + // With a loadable prntvpt.dll (the host's, copied in) only the PDF check still fails: it + // checks Windows.Data.Pdf.dll itself, not just the Print Ticket API. + let tickets = system_dll(dir.path(), PRINT_TICKET_DLL); + if system_dll_loads(PRINT_TICKET_DLL) && std::fs::copy(system_dll(&system_root(), PRINT_TICKET_DLL), &tickets).is_ok() { + assert_eq!(require_print_tickets_at(dir.path()).is_ok(), dll_loads(&tickets)); + assert!(require_windows_pdf_at(dir.path()).is_err(), "Windows.Data.Pdf.dll is still a stub"); + } + // The wrappers follow the loader on the real Windows directory (a stripped image may lack either). + let host_tickets = system_dll_loads(PRINT_TICKET_DLL); + assert_eq!(require_print_tickets().is_ok(), host_tickets); + assert_eq!(require_windows_pdf().is_ok(), system_dll_loads(WINDOWS_PDF_DLL) && host_tickets); } +/// Off Windows there are no Windows print components to check, so both checks pass. #[cfg(not(target_os = "windows"))] #[test] fn the_windows_pdf_check_is_a_no_op_elsewhere() { From 5272d227c6ca848ec2350e70facc04c8faeb4791 Mon Sep 17 00:00:00 2001 From: Higgs32584 Date: Tue, 3 Nov 2026 10:07:48 -0500 Subject: [PATCH 05/22] Document the functions the delay-load change touches Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/build.rs | 1 + apps/photocraft/build.rs | 1 + apps/photocraft/tests/windows_delay_loads.rs | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index f911223974..8983b9c8d6 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -5,6 +5,7 @@ //! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a //! build error. +/// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272). fn main() -> std::io::Result<()> { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 70a14b833e..48ce637a52 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -4,6 +4,7 @@ //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +/// Embeds the Windows resources and delay-loads the print-only system DLLs (#5884, #8272). fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); diff --git a/apps/photocraft/tests/windows_delay_loads.rs b/apps/photocraft/tests/windows_delay_loads.rs index b047614dd1..f7b7504ced 100644 --- a/apps/photocraft/tests/windows_delay_loads.rs +++ b/apps/photocraft/tests/windows_delay_loads.rs @@ -7,6 +7,7 @@ /// Loaded on first use by the print commands, which check them first. const PRINT_ONLY: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; +/// The built exe names each print-only DLL in its delay-load table, never its import table. #[test] fn print_only_system_dlls_are_delay_loaded() { let exe = std::fs::read(env!("CARGO_BIN_EXE_photocraft")).unwrap(); @@ -30,6 +31,7 @@ struct Pe<'a> { } impl<'a> Pe<'a> { + /// Reads the PE headers and section table of a PE32+ image, panicking (a test) on any other. fn parse(bytes: &'a [u8]) -> Self { let pe = u32_at(bytes, 0x3c) as usize; assert_eq!(&bytes[pe..pe + 4], b"PE\0\0"); @@ -48,6 +50,7 @@ impl<'a> Pe<'a> { Pe { bytes, sections, directories: optional + 112 } } + /// The file offset of relative virtual address `rva`, through the section that holds it. fn offset(&self, rva: u32) -> usize { let &(va, _, raw) = self.sections.iter().find(|&&(va, size, _)| rva >= va && rva < va + size).unwrap(); (rva - va + raw) as usize @@ -73,10 +76,12 @@ impl<'a> Pe<'a> { } } +/// The little-endian `u16` at byte offset `at`. fn u16_at(b: &[u8], at: usize) -> u16 { u16::from_le_bytes([b[at], b[at + 1]]) } +/// The little-endian `u32` at byte offset `at`. fn u32_at(b: &[u8], at: usize) -> u32 { u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) } From 298caecc03a7c9b1c6fcba31256a4e47584423e7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:41:37 -0500 Subject: [PATCH 06/22] engine: delegate CUBE serialization to craft-cms Retain composition and document depth policy; shared writer owns annotated header and precision. Preserve Trevor Brown original exporter behavior and existing header/quantization regressions. --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/engine/src/cmd/file_cmds/export.rs | 35 +++++++------------ .../export_clut_cube_header_tests.rs | 23 ++++++++++++ 4 files changed, 38 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c0e3142ebd..c273d0eb4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991" +source = "git+https://github.com/storytold/craft-libs?rev=6dfb580c08aeacfb0f30f79900d392394a14e798#6dfb580c08aeacfb0f30f79900d392394a14e798" dependencies = [ "md-5", "rayon", diff --git a/Cargo.toml b/Cargo.toml index 1ec3fe6b37..b727cbaf83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,7 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6dfb580c08aeacfb0f30f79900d392394a14e798" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 4021673ea8..1bc8bfe9ad 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -176,28 +176,19 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocra lattice.layers.push(a); } let out = photocraft_compose::flatten(&lattice); - // The reference application's comment layout. There is no Copyright input yet (#13748), so the - // `#Copyright:` line is never written. - let mut s = format!( - "#Created by: PhotoCraft\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {n}\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n", - title.replace('"', "'") - ); - // 8- and 16-bit documents write values on 1/32768 steps; 32-bit stays unquantised. - let quantise = |v: f32| -> f32 { - let v = v.clamp(0.0, 1.0); - if matches!(depth, photocraft_color::SampleType::F32) { v } else { (v * 32768.0).round() / 32768.0 } - }; - // .cube order: red changes fastest, then green, then blue. - for b in 0..n { - for g in 0..n { - for r in 0..n { - let (x, y) = (b * n + r, g); - let px = out.px[y * w as usize + x]; - s.push_str(&format!("{:.6} {:.6} {:.6}\n", quantise(px[0]), quantise(px[1]), quantise(px[2]))); - } - } - } - s + // Composition is app policy; the shared writer owns CUBE syntax and export precision. + let data = (0..n) + .flat_map(|b| (0..n).flat_map(move |g| (0..n).map(move |r| (b, g, r)))) + .flat_map(|(b, g, r)| { + let px = out.px[g * w as usize + b * n + r]; + [px[0], px[1], px[2]].map(|v| v.clamp(0.0, 1.0)) + }) + .collect(); + let lut = craft_cms::lutfile::LutFile { title: title.into(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }; + craft_cms::lutfile::write_cube_with_options( + &lut, + craft_cms::lutfile::CubeWriteOptions { created_by: Some("PhotoCraft"), quantize_15_bit: !matches!(depth, photocraft_color::SampleType::F32) }, + ) } /// Backwards-compatible helper for exporting all visible top-level adjustments. diff --git a/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs index 1d12a0459a..6b1315f145 100644 --- a/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs +++ b/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs @@ -89,3 +89,26 @@ fn exported_text_parses_back_with_the_same_values() { } } } + +#[test] +fn shared_writer_keeps_empty_and_quoted_titles_and_red_fastest_order() { + let mut s = session(32); + for (title, escaped) in [("", ""), ("A \"look\"", "A 'look'")] { + let result = s.execute("file.export.colorLookupTables", json!({"size": 2, "title": title})).unwrap(); + let text = result["cube"].as_str().unwrap(); + assert_eq!(text.lines().nth(1).unwrap(), format!("TITLE \"{escaped}\"")); + assert_eq!( + data_lines(text), + [ + "1.000000 1.000000 1.000000", + "0.000000 1.000000 1.000000", + "1.000000 0.000000 1.000000", + "0.000000 0.000000 1.000000", + "1.000000 1.000000 0.000000", + "0.000000 1.000000 0.000000", + "1.000000 0.000000 0.000000", + "0.000000 0.000000 0.000000", + ] + ); + } +} From 210d6da81881ccc734626e294ee704a2f0fadd89 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 06:50:14 -0500 Subject: [PATCH 07/22] engine: stream baked LUT rows without an extra RGB allocation --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/engine/src/cmd/file_cmds/export.rs | 19 ++++++------------- 3 files changed, 8 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c273d0eb4a..340f710de7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1352,7 +1352,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6dfb580c08aeacfb0f30f79900d392394a14e798#6dfb580c08aeacfb0f30f79900d392394a14e798" +source = "git+https://github.com/storytold/craft-libs?rev=c4ed8d3a84caf683132e51db94293e3aab3b111b#c4ed8d3a84caf683132e51db94293e3aab3b111b" dependencies = [ "md-5", "rayon", diff --git a/Cargo.toml b/Cargo.toml index b727cbaf83..4a6efeccd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,7 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "6dfb580c08aeacfb0f30f79900d392394a14e798" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c4ed8d3a84caf683132e51db94293e3aab3b111b" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" } diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 1bc8bfe9ad..a792f629f4 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -176,19 +176,12 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocra lattice.layers.push(a); } let out = photocraft_compose::flatten(&lattice); - // Composition is app policy; the shared writer owns CUBE syntax and export precision. - let data = (0..n) - .flat_map(|b| (0..n).flat_map(move |g| (0..n).map(move |r| (b, g, r)))) - .flat_map(|(b, g, r)| { - let px = out.px[g * w as usize + b * n + r]; - [px[0], px[1], px[2]].map(|v| v.clamp(0.0, 1.0)) - }) - .collect(); - let lut = craft_cms::lutfile::LutFile { title: title.into(), size: n, data, domain_min: [0.0; 3], domain_max: [1.0; 3] }; - craft_cms::lutfile::write_cube_with_options( - &lut, - craft_cms::lutfile::CubeWriteOptions { created_by: Some("PhotoCraft"), quantize_15_bit: !matches!(depth, photocraft_color::SampleType::F32) }, - ) + // The shared writer owns CUBE syntax and precision; baking stays app-local. + let rows = (0..n).flat_map(|b| (0..n).flat_map(move |g| (0..n).map(move |r| (b, g, r)))).map(|(b, g, r)| { + let px = out.px[g * w as usize + b * n + r]; + [px[0], px[1], px[2]] + }); + craft_cms::lutfile::write_cube_export("PhotoCraft", title, n, !matches!(depth, photocraft_color::SampleType::F32), rows) } /// Backwards-compatible helper for exporting all visible top-level adjustments. From 4bd0727b9fd98b11afec7f9dd986eb4ba30da51e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 15 Nov 2026 09:27:42 -0500 Subject: [PATCH 08/22] test(io): retain original annotation writer as parity oracle Source: PhotoCraft aa87012a and saturation correction 0d6e58e2. Frozen test-only writer; application adaptation follows separately. Co-authored-by: wstock --- crates/io/src/annotation_shared_tests.rs | 63 ++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 crates/io/src/annotation_shared_tests.rs diff --git a/crates/io/src/annotation_shared_tests.rs b/crates/io/src/annotation_shared_tests.rs new file mode 100644 index 0000000000..5d8f773e01 --- /dev/null +++ b/crates/io/src/annotation_shared_tests.rs @@ -0,0 +1,63 @@ +//! Frozen valid-wire writer oracle from PhotoCraft5bdbcc118. +//! Original wire writer Brandon Thomas aa87012a; saturating icon fix wstock0d6e58e2. +use super::*; +fn pascal(out: &mut Vec, s: &str) { + let bytes: Vec = s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect(); + out.push(bytes.len() as u8); + out.extend_from_slice(&bytes); + if (bytes.len() + 1) % 2 == 1 { + out.push(0); + } +} + +fn legacy_note(n: &Note) -> Vec { + let mut b = Vec::new(); + b.extend_from_slice(b"txtA"); + b.push(u8::from(n.open)); + b.push(0x1C); + b.extend_from_slice(&1u16.to_be_bytes()); + // The position comes from the file or a command and can sit anywhere in i32 (issue #939): + // the cast saturates, and the icon's far edge must saturate too rather than wrap (release) or + // overflow (debug) when the note is re-saved. + let (x, y) = (n.position[0].round() as i32, n.position[1].round() as i32); + for v in [y, x, y.saturating_add(20), x.saturating_add(16)] { + b.extend_from_slice(&v.to_be_bytes()); + } + let pp = if n.popup == [0.0; 4] { [n.position[0] + 20.0, n.position[1] + 20.0, n.position[0] + 260.0, n.position[1] + 160.0] } else { n.popup }; + for v in [pp[1], pp[0], pp[3], pp[2]] { + b.extend_from_slice(&(v.round() as i32).to_be_bytes()); + } + b.extend_from_slice(&0u16.to_be_bytes()); + let rgb = n.color.to_rgb(); + for v in rgb { + b.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes()); + } + b.extend_from_slice(&0u16.to_be_bytes()); + pascal(&mut b, &n.author); + pascal(&mut b, ""); + pascal(&mut b, &n.modified); + let text = encode_text(&n.text); + b.extend_from_slice(&((text.len() + 12) as u32).to_be_bytes()); + b.extend_from_slice(b"txtC"); + b.extend_from_slice(&(text.len() as u32).to_be_bytes()); + b.extend_from_slice(&text); + let mut out = ((b.len() + 4) as u32).to_be_bytes().to_vec(); + out.extend_from_slice(&b); + out +} + +/// An `Anno` block holding `notes` (plus raw sound entries carried over). +fn legacy_anno(notes: &[Note], raw_extra: &[Vec]) -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(&2u16.to_be_bytes()); + out.extend_from_slice(&1u16.to_be_bytes()); + out.extend_from_slice(&((notes.len() + raw_extra.len()) as u32).to_be_bytes()); + for n in notes { + out.extend_from_slice(&legacy_note(n)); + } + for r in raw_extra { + out.extend_from_slice(r); + } + out +} + From db0ff2778eae468f1531d5d21f83c2a4a08fc2b5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 09:27:42 -0500 Subject: [PATCH 09/22] io: delegate PSD annotations to shared bounded codec --- Cargo.lock | 2 +- Cargo.toml | 2 +- crates/io/src/annotation_shared_tests.rs | 29 +++ crates/io/src/annotations_map.rs | 224 ++++++++------------ crates/io/src/lib.rs | 2 +- crates/io/src/multichannel_map.rs | 12 +- crates/io/src/palette_map.rs | 14 +- crates/io/src/pattern_map.rs | 2 +- crates/io/src/psd_export.rs | 3 +- crates/io/src/psd_export/document.rs | 30 +-- crates/io/src/psd_export/tests.rs | 25 +-- crates/io/src/tiff_layers.rs | 4 +- crates/io/tests/it/deflate_compatibility.rs | 4 +- crates/io/tests/it/roundtrip.rs | 2 +- crates/io/tests/it/tiff_layers.rs | 2 +- crates/io/tests/it/tiff_type_geometry.rs | 10 +- 16 files changed, 177 insertions(+), 190 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63bd18fb44..291e70b68c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1589,7 +1589,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" +source = "git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f#2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" dependencies = [ "encoding_rs", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 187d840235..f1edbbf1d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,7 @@ photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" } photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" } photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } diff --git a/crates/io/src/annotation_shared_tests.rs b/crates/io/src/annotation_shared_tests.rs index 5d8f773e01..dd77d18e06 100644 --- a/crates/io/src/annotation_shared_tests.rs +++ b/crates/io/src/annotation_shared_tests.rs @@ -61,3 +61,32 @@ fn legacy_anno(notes: &[Note], raw_extra: &[Vec]) -> Vec { out } +#[test] +fn shared_writer_matches_valid_legacy_bytes() { + for text in ["", "ascii", "hΓ©llo βœ“", "one\r\ntwo\nthree", "π„ž"] { + for x in [0.0, -5.5, f64::from(i32::MAX), f64::INFINITY] { + let note = Note { text: text.into(), author: "Γ€βœ“".repeat(180), modified: "date".into(), position: [x, 2.5], ..Default::default() }; + let extra = vec![vec![0, 0, 0, 8, b's', b'n', b'd', b'A']]; + assert_eq!(write_anno(&[note.clone()], &extra).unwrap(), legacy_anno(&[note], &extra)); + } + } +} +#[test] +fn every_export_path_refuses_excess_notes() { + for mode in [photocraft_doc::ColorMode::Rgb, photocraft_doc::ColorMode::Multichannel, photocraft_doc::ColorMode::Bitmap] { + let mut d = Document::new("notes", photocraft_doc::Size::new(1, 1), mode, photocraft_doc::SampleType::U8); + d.notes = vec![Note::default(); 4097]; + assert!(export_blocks(&d, vec![]).is_err()); + assert!(crate::document_to_psd(&d).is_err()); + assert!(crate::document_to_psd_with(&d, &Default::default()).is_err()); + assert!(crate::encode_with(&d, "psd", &Default::default(), &photocraft_raster::Interrupt::NONE).is_err()); + assert!(crate::encode_with(&d, "tiff", &Default::default(), &photocraft_raster::Interrupt::NONE).is_err()); + } +} +#[test] +fn text_cannot_cross_declared_record_boundary() { + let mut block = write_anno(&[Note { text: "payload".into(), ..Default::default() }], &[]).unwrap(); + let length = u32::from_be_bytes(block[8..12].try_into().unwrap()); + block[8..12].copy_from_slice(&(length - 2).to_be_bytes()); + assert!(parse_entries(&block).is_none()); +} diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index 9f95f6eb3b..acc802fa60 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -26,46 +26,8 @@ pub const MEASUREMENT_SCALE: u16 = 1074; pub const COUNT_INFO: u16 = 1080; pub const ANNO: [u8; 4] = *b"Anno"; -struct Reader<'a> { - d: &'a [u8], - p: usize, -} - -impl<'a> Reader<'a> { - fn take(&mut self, n: usize) -> Option<&'a [u8]> { - let s = self.d.get(self.p..self.p.checked_add(n)?)?; - self.p += n; - Some(s) - } - fn u8(&mut self) -> Option { - self.take(1).map(|b| b[0]) - } - fn u16(&mut self) -> Option { - self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]])) - } - fn u32(&mut self) -> Option { - self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])) - } - fn i32(&mut self) -> Option { - self.u32().map(|v| v as i32) - } - fn pascal(&mut self) -> Option { - let n = usize::from(self.u8()?); - let s = self.take(n)?; - if (n + 1) % 2 == 1 { - self.take(1)?; - } - Some(s.iter().map(|&c| c as char).collect()) - } -} - -fn pascal(out: &mut Vec, s: &str) { - let bytes: Vec = s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect(); - out.push(bytes.len() as u8); - out.extend_from_slice(&bytes); - if (bytes.len() + 1) % 2 == 1 { - out.push(0); - } +fn pascal_bytes(s: &str) -> Vec { + s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect() } /// PSD colour struct (space + 4 Γ— u16) β†’ RGB. @@ -127,51 +89,24 @@ enum Entry { } fn parse_entries(data: &[u8]) -> Option> { - let mut r = Reader { d: data, p: 0 }; - let (_major, _minor) = (r.u16()?, r.u16()?); - let count = r.u32()? as usize; - let mut out = Vec::with_capacity(count.min(4096)); - for _ in 0..count { - let start = r.p; - let len = r.u32()? as usize; - // The length counts itself and the type: anything shorter would put the cursor back on - // this entry, and a hostile count would then loop until memory runs out. - if len < 8 { - return None; - } - let end = start.checked_add(len)?; - let raw = data.get(start..end)?; - let kind = r.take(4)?; - if kind != b"txtA" { - out.push(Entry::Raw(raw.to_vec())); - r.p = end; - continue; - } - let open = r.u8()? != 0; - let (_flags, _opt) = (r.u8()?, r.u16()?); - let icon = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let popup = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let space = r.u16()?; - let c = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; - let author = r.pascal()?; - let _name = r.pascal()?; - let modified = r.pascal()?; - let _data_len = r.u32()?; - let _key = r.take(4)?; - let n = r.u32()? as usize; - let text = decode_text(r.take(n)?); - out.push(Entry::Text(Note { - author, - color: color_from(space, c), - text, - position: [f64::from(icon[1]), f64::from(icon[0])], - popup: [f64::from(popup[1]), f64::from(popup[0]), f64::from(popup[3]), f64::from(popup[2])], - open, - modified, - })); - r.p = end; - } - Some(out) + let records = craft_psd::annotations::read(data, Default::default()).ok()?; + records + .into_iter() + .map(|r| { + let Some(t) = r.text().ok()? else { + return Some(Entry::Raw(r.raw().to_vec())); + }; + Some(Entry::Text(Note { + author: t.author.iter().map(|&c| c as char).collect(), + color: color_from(t.color_space, t.color), + text: decode_text(t.data), + position: [f64::from(t.icon[1]), f64::from(t.icon[0])], + popup: [f64::from(t.popup[1]), f64::from(t.popup[0]), f64::from(t.popup[3]), f64::from(t.popup[2])], + open: t.open != 0, + modified: t.modified.iter().map(|&c| c as char).collect(), + })) + }) + .collect() } /// Notes in an `Anno` block (None when it doesn't parse). @@ -179,55 +114,60 @@ pub fn parse_anno(data: &[u8]) -> Option> { Some(parse_entries(data)?.into_iter().filter_map(|e| if let Entry::Text(n) = e { Some(n) } else { None }).collect()) } -fn write_note(n: &Note) -> Vec { - let mut b = Vec::new(); - b.extend_from_slice(b"txtA"); - b.push(u8::from(n.open)); - b.push(0x1C); - b.extend_from_slice(&1u16.to_be_bytes()); - // The position comes from the file or a command and can sit anywhere in i32 (issue #939): - // the cast saturates, and the icon's far edge must saturate too rather than wrap (release) or - // overflow (debug) when the note is re-saved. +fn write_note(n: &Note) -> craft_psd::Result> { + let limits = craft_psd::annotations::Limits::default(); + // Bound temporary text normalization before the shared fallible writer allocates. + if n.text.len().checked_mul(2).and_then(|n| n.checked_add(2)).is_none_or(|n| n > limits.bytes) { + return Err(craft_psd::PsdError::LimitExceeded("annotation text")); + } let (x, y) = (n.position[0].round() as i32, n.position[1].round() as i32); - for v in [y, x, y.saturating_add(20), x.saturating_add(16)] { - b.extend_from_slice(&v.to_be_bytes()); - } let pp = if n.popup == [0.0; 4] { [n.position[0] + 20.0, n.position[1] + 20.0, n.position[0] + 260.0, n.position[1] + 160.0] } else { n.popup }; - for v in [pp[1], pp[0], pp[3], pp[2]] { - b.extend_from_slice(&(v.round() as i32).to_be_bytes()); - } - b.extend_from_slice(&0u16.to_be_bytes()); let rgb = n.color.to_rgb(); - for v in rgb { - b.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_be_bytes()); - } - b.extend_from_slice(&0u16.to_be_bytes()); - pascal(&mut b, &n.author); - pascal(&mut b, ""); - pascal(&mut b, &n.modified); + let author = pascal_bytes(&n.author); + let modified = pascal_bytes(&n.modified); let text = encode_text(&n.text); - b.extend_from_slice(&((text.len() + 12) as u32).to_be_bytes()); - b.extend_from_slice(b"txtC"); - b.extend_from_slice(&(text.len() as u32).to_be_bytes()); - b.extend_from_slice(&text); - let mut out = ((b.len() + 4) as u32).to_be_bytes().to_vec(); - out.extend_from_slice(&b); - out + craft_psd::annotations::write_text( + &craft_psd::annotations::Text { + open: u8::from(n.open), + flags: 0x1C, + optional_blocks: 1, + icon: [y, x, y.saturating_add(20), x.saturating_add(16)], + popup: [pp[1].round() as i32, pp[0].round() as i32, pp[3].round() as i32, pp[2].round() as i32], + color_space: 0, + color: [ + (rgb[0].clamp(0.0, 1.0) * 65535.0).round() as u16, + (rgb[1].clamp(0.0, 1.0) * 65535.0).round() as u16, + (rgb[2].clamp(0.0, 1.0) * 65535.0).round() as u16, + 0, + ], + author: &author, + name: &[], + modified: &modified, + data_length: 0, + data_key: *b"txtC", + data: &text, + }, + limits, + ) } -/// An `Anno` block holding `notes` (plus raw sound entries carried over). -pub fn write_anno(notes: &[Note], raw_extra: &[Vec]) -> Vec { - let mut out = Vec::new(); - out.extend_from_slice(&2u16.to_be_bytes()); - out.extend_from_slice(&1u16.to_be_bytes()); - out.extend_from_slice(&((notes.len() + raw_extra.len()) as u32).to_be_bytes()); +/// An Anno block holding notes and byte-exact unknown records. +/// Errors propagate to export instead of silently dropping annotations. +pub fn write_anno(notes: &[Note], raw_extra: &[Vec]) -> craft_psd::Result> { + let limits = craft_psd::annotations::Limits::default(); + if notes.len().checked_add(raw_extra.len()).is_none_or(|n| n > limits.records) { + return Err(craft_psd::PsdError::LimitExceeded("annotation count")); + } + let mut owned = Vec::new(); + owned.try_reserve_exact(notes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("annotation records"))?; + let mut bytes = 8usize; for n in notes { - out.extend_from_slice(&write_note(n)); + let record = write_note(n)?; + bytes = bytes.checked_add(record.len()).filter(|&n| n <= limits.bytes).ok_or(craft_psd::PsdError::LimitExceeded("annotation bytes"))?; + owned.push(record); } - for r in raw_extra { - out.extend_from_slice(r); - } - out + let refs: Vec<&[u8]> = owned.iter().chain(raw_extra).map(Vec::as_slice).collect(); + craft_psd::annotations::write(&refs, limits) } /// The document's notes from its raw global blocks (empty when there is no `Anno` block). @@ -243,14 +183,14 @@ pub fn anno_unreadable(doc: &Document) -> bool { /// Global blocks to write: the raw `Anno` block while it still describes `doc.notes` (or doesn't /// parse and no note was added), else a regenerated one in its place (appended when new, dropped /// when the last note is deleted). -pub fn export_blocks(doc: &Document, mut blocks: Vec) -> Vec { +pub fn export_blocks(doc: &Document, mut blocks: Vec) -> Result, crate::IoError> { let at = blocks.iter().position(|(_, k, _)| *k == ANNO); let raw = at.map(|i| blocks[i].2.clone()); let entries = raw.as_deref().and_then(|d| parse_entries(d)); let parsed: Option> = entries.as_ref().map(|e| e.iter().filter_map(|e| if let Entry::Text(n) = e { Some(n.clone()) } else { None }).collect()); // Compare in stored precision (colours are 16-bit, positions whole pixels, empty popups get a // default rectangle). - let want = parse_anno(&write_anno(&doc.notes, &[])); + let want = parse_anno(&write_anno(&doc.notes, &[]).map_err(|e| crate::IoError::Unsupported(e.to_string()))?); let same = |a: &[Note], b: &[Note]| { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| { @@ -261,10 +201,14 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec> = entries.unwrap_or_default().into_iter().filter_map(|e| if let Entry::Raw(r) = e { Some(r) } else { None }).collect(); - let fresh = (!doc.notes.is_empty() || !extra.is_empty()).then(|| Arc::new(write_anno(&doc.notes, &extra))); + let fresh = if !doc.notes.is_empty() || !extra.is_empty() { + Some(Arc::new(write_anno(&doc.notes, &extra).map_err(|e| crate::IoError::Unsupported(e.to_string()))?)) + } else { + None + }; match (at, fresh) { (Some(i), Some(f)) => blocks[i].2 = f, (Some(i), None) => { @@ -273,7 +217,7 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec blocks.push((*b"8BIM", ANNO, f)), (None, None) => {} } - blocks + Ok(blocks) } fn num(v: &Value) -> Option { @@ -488,7 +432,7 @@ mod tests { // Hue 343Β°, saturation 0.49, brightness 1: pink. assert!(rgb[0] > 0.99 && rgb[1] < rgb[2] && rgb[2] < 0.7, "{rgb:?}"); // Text, positions, flags and RGB colours are rewritten exactly. - let again = write_anno(¬es[..1], &[]); + let again = write_anno(¬es[..1], &[]).unwrap(); assert_eq!(parse_anno(&again).unwrap()[..], notes[..1]); let n0 = 8 + u32::from_be_bytes(raw[8..12].try_into().unwrap()) as usize; assert_eq!(&again[8..], &raw[8..n0]); @@ -497,16 +441,16 @@ mod tests { #[test] fn export_blocks_keeps_replaces_and_drops() { let mut d = Document::new("n", photocraft_doc::Size::new(10, 10), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - assert!(export_blocks(&d, vec![]).is_empty()); + assert!(export_blocks(&d, vec![]).unwrap().is_empty()); d.notes.push(Note { text: "hΓ©llo βœ“".into(), author: "me".into(), position: [3.0, 4.0], ..Default::default() }); - let out = export_blocks(&d, vec![]); + let out = export_blocks(&d, vec![]).unwrap(); assert_eq!(out.len(), 1); assert_eq!(parse_anno(&out[0].2).unwrap()[0].text, "hΓ©llo βœ“"); // Unchanged β†’ the very same bytes. d.metadata.psd_global_blocks = out.clone(); - assert!(Arc::ptr_eq(&export_blocks(&d, out.clone())[0].2, &out[0].2)); + assert!(Arc::ptr_eq(&export_blocks(&d, out.clone()).unwrap()[0].2, &out[0].2)); d.notes.clear(); - assert!(export_blocks(&d, out).is_empty()); + assert!(export_blocks(&d, out).unwrap().is_empty()); assert!(parse_anno(&[0, 2, 0, 1, 0, 0, 0, 9]).is_none()); } @@ -517,12 +461,12 @@ mod tests { let bad: Vec = vec![(*b"8BIM", ANNO, Arc::new(vec![0, 2, 0, 1, 0, 0, 0, 9]))]; d.metadata.psd_global_blocks = bad.clone(); assert!(anno_unreadable(&d) && notes_from_blocks(&d).is_empty()); - let out = export_blocks(&d, bad.clone()); + let out = export_blocks(&d, bad.clone()).unwrap(); assert_eq!(out.len(), 1); assert!(Arc::ptr_eq(&out[0].2, &bad[0].2)); // A note added by the user still writes a fresh block in its place. d.notes.push(Note { text: "new".into(), ..Default::default() }); - let out = export_blocks(&d, bad); + let out = export_blocks(&d, bad).unwrap(); assert_eq!(parse_anno(&out[0].2).unwrap()[0].text, "new"); // A readable block is not reported. d.metadata.psd_global_blocks = out; @@ -562,3 +506,7 @@ mod tests { assert!(!keep_resource(&d, COUNT_INFO)); } } + +#[cfg(test)] +#[path = "annotation_shared_tests.rs"] +mod shared_tests; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index c6e8e25d8e..06ee45a7f6 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1244,7 +1244,7 @@ fn export_stages_with_renderer( // The preview is rendered first, while only the document is in memory: its full-size // render would otherwise come on top of the finished file model (#6607). let preview = opts.image_previews.then(|| psd_thumbnail::resource(doc)); - let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl)); + let (mut file, mut warnings) = with_span(ctl, 0.0, PSD_MODEL_DONE, |ctl| psd_export::document_to_psd_interruptible(doc, &o, ctl))?; // A cancelled conversion stops early with an incomplete model: never write it. ctl.check().map_err(|_| IoError::Cancelled)?; if !doc.metadata.text.is_empty() { diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index 108b1931b1..6c3971d3fb 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -102,7 +102,7 @@ pub(crate) fn document_to_psd( force_psb: bool, size_limit: Option, patterns: Option<&[photocraft_doc::PsdGlobalBlock]>, -) -> (PsdFile, Vec) { +) -> Result<(PsdFile, Vec), crate::IoError> { let mut warnings = Vec::new(); // Photoshop's Multichannel mode is 8 or 16 bits per channel. let sample = match doc.depth { @@ -159,8 +159,8 @@ pub(crate) fn document_to_psd( // Alpha identifiers: one u32 per channel, only while they still match the channels. let keep = |id: u16, data: &[u8]| id != ALPHA_IDENTIFIERS || data.len() == channels.len().saturating_mul(4); let color_mode_data = craft_psd::hdr::color_mode_data_for_depth(header.depth); - let file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings, patterns); - (file, warnings) + let file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings, patterns)?; + Ok((file, warnings)) } /// A PSD without layers around `image_data`: `resources` (the mode's own) plus the paths, XMP, @@ -179,7 +179,7 @@ pub(crate) fn layerless_file( size_limit: Option, warnings: &mut Vec, patterns: Option<&[photocraft_doc::PsdGlobalBlock]>, -) -> PsdFile { +) -> Result { resources.extend(crate::psd_export::path_resources(doc, warnings)); // The XMP and EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it. let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); @@ -209,7 +209,7 @@ pub(crate) fn layerless_file( // kept layer block would describe layers the document doesn't have. Their signatures follow // the version the file is written as, known once its size is. let patterns = patterns.map_or_else(|| crate::pattern_map::export_global_blocks_with_warnings(doc, warnings), <[_]>::to_vec); - let global_blocks: Vec = crate::annotations_map::export_blocks(doc, patterns) + let global_blocks: Vec = crate::annotations_map::export_blocks(doc, patterns)? .into_iter() .filter(|(_, key, _)| !matches!(key, b"Layr" | b"Lr16" | b"Lr32")) .map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data)) @@ -232,7 +232,7 @@ pub(crate) fn layerless_file( warnings.push(warning); } crate::psd_export::sign_global_blocks(&mut file); - file + Ok(file) } #[cfg(test)] diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index 022bcaa24b..0e30c2098a 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -28,18 +28,20 @@ pub(crate) fn document_to_psd( force_psb: bool, size_limit: Option, patterns: Option<&[photocraft_doc::PsdGlobalBlock]>, -) -> Option<(PsdFile, Vec)> { +) -> Result)>, crate::IoError> { if !doc.channels.is_empty() || doc.quick_mask.is_some() { - return None; + return Ok(None); } let table = doc.color_table.as_ref().filter(|t| t.colors.len() <= 256 && (0..t.colors.len()).any(|i| Some(i) != t.transparent.map(usize::from))); let (mode, plane, color_mode_data) = match doc.mode { ColorMode::Indexed => { - let table = table?; + let Some(table) = table else { + return Ok(None); + }; (PsdMode::Indexed, indices(doc, table), palette(table)) } ColorMode::Bitmap => (PsdMode::Bitmap, bits(doc), Vec::new()), - _ => return None, + _ => return Ok(None), }; let mut warnings = Vec::new(); if !flattens_losslessly(doc) { @@ -70,8 +72,8 @@ pub(crate) fn document_to_psd( } // An imported transparency index that no longer applies is not copied either. let keep = |id: u16, _: &[u8]| !CHANNEL_RESOURCES.contains(&id) && id != TRANSPARENCY_INDEX && id != COLOR_TABLE_COUNT; - let file = crate::multichannel_map::layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings, patterns); - Some((file, warnings)) + let file = crate::multichannel_map::layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings, patterns)?; + Ok(Some((file, warnings))) } /// Whether the merged image holds everything the layers do: no layer, or a single visible pixel diff --git a/crates/io/src/pattern_map.rs b/crates/io/src/pattern_map.rs index 1a7ba6d592..e7c55bc0ce 100644 --- a/crates/io/src/pattern_map.rs +++ b/crates/io/src/pattern_map.rs @@ -501,7 +501,7 @@ mod allocation_tests { assert!(export_global_blocks(&loaded).unwrap_err().contains("Oversized retained pattern")); for force_psb in [false, true] { let opts = crate::PsdExportOptions { force_psb, ..Default::default() }; - let (file, warnings) = crate::document_to_psd_with(&loaded, &opts); + let (file, warnings) = crate::document_to_psd_with(&loaded, &opts).unwrap(); assert!( warnings.iter().any(|w| w.contains("Oversized retained pattern") && w.contains("omitted from PSD/PSB")), "{mode:?} {depth:?}: {warnings:?}" diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index f8a01dd5af..343c5e228c 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -964,7 +964,8 @@ impl Ex<'_> { &PsdExportOptions { force_psb: true, document_path: self.document.clone(), read_linked_files: self.read_linked_files, ..Default::default() }, self.smart.depth + 1, &Interrupt::NONE, - ); + ) + .map_err(|e| format!("its annotations cannot be written: {e}"))?; let data = file.to_bytes().map_err(|e| format!("its contents can't be written: {e}"))?; let stem = file_name.rsplit_once('.').map_or(file_name, |(a, _)| a); self.warnings.extend(warnings.into_iter().map(|w| format!("smart object {stem}: {w}"))); diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 1c8692dbc9..c28f44d1e6 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -18,30 +18,36 @@ pub fn document_to_psd(doc: &Document) -> Result { fn document_to_psd_with_pattern_limit(doc: &Document, limit: u64) -> Result { let patterns = crate::pattern_map::export_global_blocks_with_limit(doc, limit).map_err(crate::IoError::Unsupported)?; - Ok(document_to_psd_sized_with_patterns(doc, &PsdExportOptions::default(), 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE, Some(&patterns)).0) + Ok(document_to_psd_sized_with_patterns(doc, &PsdExportOptions::default(), 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE, Some(&patterns))?.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) { +pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> Result<(PsdFile, Vec), crate::IoError> { document_to_psd_sized(doc, opts, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE) } /// [`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) { +pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> Result<(PsdFile, Vec), crate::IoError> { document_to_psd_sized(doc, opts, 0, ctl, PSD_MAX_FILE_SIZE) } /// [`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) { +pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> Result<(PsdFile, Vec), crate::IoError> { document_to_psd_sized(doc, opts, depth, ctl, PSD_MAX_FILE_SIZE) } /// Export with a caller-selected PSD size limit; the test suite lowers it to exercise promotion. -pub(super) fn document_to_psd_sized(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt, size_limit: u64) -> (PsdFile, Vec) { +pub(super) fn document_to_psd_sized( + doc: &Document, + opts: &PsdExportOptions, + depth: u32, + ctl: &Interrupt, + size_limit: u64, +) -> Result<(PsdFile, Vec), crate::IoError> { document_to_psd_sized_with_patterns(doc, opts, depth, ctl, size_limit, None) } @@ -52,13 +58,13 @@ fn document_to_psd_sized_with_patterns( ctl: &Interrupt, size_limit: u64, patterns: Option<&[photocraft_doc::PsdGlobalBlock]>, -) -> (PsdFile, Vec) { +) -> Result<(PsdFile, Vec), crate::IoError> { let layerless_limit = opts.size_limit_psb.then_some(size_limit); if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns); } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns) { - return file; + if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + return Ok(file); } let fmt = doc.pixel_format(); export_supported_document(doc, opts, depth, ctl, fmt, size_limit, patterns) @@ -72,7 +78,7 @@ fn export_supported_document( fmt: PixelFormat, size_limit: u64, patterns: Option<&[photocraft_doc::PsdGlobalBlock]>, -) -> (PsdFile, Vec) { +) -> Result<(PsdFile, Vec), crate::IoError> { // 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. @@ -178,7 +184,7 @@ fn export_supported_document( // The warning-free entry point has already encoded every pattern successfully. // Reuse those blocks rather than allocating and converting the library a second time. let patterns = patterns.map_or_else(|| crate::pattern_map::export_global_blocks_with_warnings(doc, &mut ex.warnings), <[_]>::to_vec); - let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, patterns)); + let preserved = ex.smart.finish(crate::annotations_map::export_blocks(doc, patterns)?); // 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 @@ -312,7 +318,7 @@ fn export_supported_document( ex.warnings.push(warning); } sign_global_blocks(&mut file); - (file, ex.warnings) + Ok((file, ex.warnings)) } fn add_format_warnings(doc: &Document, opts: &PsdExportOptions, fmt: PixelFormat, big: bool, has_duotone: bool, warnings: &mut Vec) { @@ -527,7 +533,7 @@ mod pattern_failure_tests { // The public warning-enabled API continues to return a complete model when // these ordinary patterns fit the production allowance. - let (_, warnings) = document_to_psd_with(&doc, &PsdExportOptions::default()); + let (_, warnings) = document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap(); assert!(!warnings.iter().any(|warning| warning.contains("omitted from PSD/PSB")), "{mode:?}: {warnings:?}"); } } diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 13f11fca7b..11eecb33ab 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -384,7 +384,7 @@ const SIZED_LIMIT: u64 = 4 * 1024 * 1024; const _: () = assert!(SIZED_RAW_BYTES > SIZED_LIMIT); fn export_sized(doc: &Document, limit: u64) -> (PsdFile, Vec) { - document_to_psd_sized(doc, &PsdExportOptions::default(), 0, &Interrupt::NONE, limit) + document_to_psd_sized(doc, &PsdExportOptions::default(), 0, &Interrupt::NONE, limit).unwrap() } /// #5285: a document whose raw pixels are over the PSD limit but whose encoded file fits is @@ -413,7 +413,7 @@ fn a_file_over_the_limit_after_compression_is_psb() { assert!(warnings.iter().any(|w| w == "encoded size exceeds 2 GB; written as PSB"), "{warnings:?}"); let bytes = file.to_bytes().unwrap(); assert!(bytes.len() as u64 > SIZED_LIMIT); - let forced = document_to_psd_with(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }).0; + let forced = document_to_psd_with(&doc, &PsdExportOptions { force_psb: true, ..Default::default() }).unwrap().0; let forced = forced.to_bytes().unwrap(); assert!(bytes == forced, "{depth:?}: the promoted PSB differs from a PSB written directly"); assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), PsdFile::from_bytes(&forced).unwrap(), "{depth:?}"); @@ -437,7 +437,7 @@ fn the_size_limit_is_the_exact_encoded_length() { // The real limit: a small document stays PSD, a forced one is PSB. let small = document(1, 1); assert_eq!(document_to_psd(&small).unwrap().written_version(), Version::Psd); - assert_eq!(document_to_psd_with(&small, &PsdExportOptions { force_psb: true, ..Default::default() }).0.written_version(), Version::Psb); + assert_eq!(document_to_psd_with(&small, &PsdExportOptions { force_psb: true, ..Default::default() }).unwrap().0.written_version(), Version::Psb); assert_eq!(psd_version(&document(30_001, 1), false), Version::Psb); } @@ -501,7 +501,7 @@ fn every_mode_promoted_by_size_signs_long_blocks_8b64() { assert_eq!(big.decode_merged().unwrap(), small.decode_merged().unwrap(), "{psd_mode:?}"); // Without `size_limit_psb` no mode is promoted by its size, the layerless ones included. let opts = PsdExportOptions { size_limit_psb: false, ..PsdExportOptions::default() }; - let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, len + PSD_SAVE_HEADROOM - 1); + let (kept, warnings) = document_to_psd_sized(&doc, &opts, 0, &Interrupt::NONE, len + PSD_SAVE_HEADROOM - 1).unwrap(); assert_eq!((kept.written_version(), kept.header.color_mode), (Version::Psd, psd_mode), "{psd_mode:?}: {warnings:?}"); assert!(!warnings.iter().any(|w| w.contains("written as PSB")), "{psd_mode:?}: {warnings:?}"); } @@ -516,7 +516,7 @@ fn kept_psb_blocks_are_written_as_8bim_in_a_psd() { 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(); + let bytes = document_to_psd_with(&doc, &opts).unwrap().0.to_bytes().unwrap(); let file = PsdFile::from_bytes(&bytes).unwrap(); file.global_blocks.iter().map(|b| (b.signature, b.key)).collect::>() }; @@ -538,7 +538,7 @@ fn psb_writes_long_length_blocks_as_8b64() { ]; let written = |force_psb| { let opts = PsdExportOptions { force_psb, ..PsdExportOptions::default() }; - let bytes = document_to_psd_with(&doc, &opts).0.to_bytes().unwrap(); + let bytes = document_to_psd_with(&doc, &opts).unwrap().0.to_bytes().unwrap(); let file = PsdFile::from_bytes(&bytes).unwrap(); let blocks = file.global_blocks.iter().map(|b| (b.signature, b.key, b.data.len())).collect::>(); (bytes, blocks) @@ -614,7 +614,7 @@ fn a_linked_fifo_is_not_read() { }; doc.layers.push(Layer::new("Linked", LayerContent::Smart(smart))); let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || tx.send(document_to_psd_with(&doc, &PsdExportOptions::default()).1)); + std::thread::spawn(move || tx.send(document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap().1)); let warnings = rx.recv_timeout(std::time::Duration::from_secs(30)).expect("the export blocked reading the FIFO"); let _ = std::fs::remove_dir_all(&dir); assert!(warnings.iter().any(|w| w.contains("smart object written as pixels") && w.contains("not a regular file")), "{warnings:?}"); @@ -632,8 +632,8 @@ fn staged_channels_write_the_same_file_as_in_memory_ones() { for (force_psb, limit) in [(false, PSD_MAX_FILE_SIZE), (true, PSD_MAX_FILE_SIZE), (false, SIZED_LIMIT)] { let plain = PsdExportOptions { force_psb, ..Default::default() }; let staged = PsdExportOptions { stage_on_scratch_from: Some(0), ..plain.clone() }; - let (want, _) = document_to_psd_sized(&doc, &plain, 0, &ctl, limit); - let (file, _) = document_to_psd_sized(&doc, &staged, 0, &ctl, limit); + let (want, _) = document_to_psd_sized(&doc, &plain, 0, &ctl, limit).unwrap(); + let (file, _) = document_to_psd_sized(&doc, &staged, 0, &ctl, limit).unwrap(); let layer = &file.layers()[0]; // The opaque alpha packs to a few KB and stays in memory; the noise colour channels go. assert!(layer.channels.iter().filter(|c| c.id >= 0).all(|c| c.stored.is_some() && c.data.is_empty()), "every noise channel is staged"); @@ -647,7 +647,8 @@ fn staged_channels_write_the_same_file_as_in_memory_ones() { assert!(w.into_inner() == bytes, "psb {force_psb}, limit {limit}: streamed staged bytes differ"); } // Under the threshold, or with no stage asked for, nothing is staged. - let (file, _) = document_to_psd_sized(&doc, &PsdExportOptions { stage_on_scratch_from: Some(u64::MAX), ..Default::default() }, 0, &ctl, PSD_MAX_FILE_SIZE); + let (file, _) = + document_to_psd_sized(&doc, &PsdExportOptions { stage_on_scratch_from: Some(u64::MAX), ..Default::default() }, 0, &ctl, PSD_MAX_FILE_SIZE).unwrap(); assert!(file.layers()[0].channels.iter().all(|c| c.stored.is_none()) && file.image_data.stored.is_none()); stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = None); #[cfg(unix)] @@ -708,7 +709,7 @@ fn banding_document(mode: ColorMode, depth: SampleType, w: u32, h: u32) -> Docum fn export_banded(doc: &Document, options: &PsdExportOptions, banded: Option) -> (PsdFile, Vec) { let row_bytes = doc.size.width as usize * doc.pixel_format().bytes_per_pixel(); banded::BANDS_FOR_TESTS.set(banded.map(|rows| (0, rows * row_bytes + 3))); - let out = document_to_psd_sized(doc, options, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE); + let out = document_to_psd_sized(doc, options, 0, &Interrupt::NONE, PSD_MAX_FILE_SIZE).unwrap(); banded::BANDS_FOR_TESTS.set(None); out } @@ -825,7 +826,7 @@ fn a_cancelled_save_stops_between_the_bands_of_a_layer() { let what = format!("{depth:?}, psb {force_psb}, staged {staged}"); stage::DIR_FOR_TESTS.with(|d| *d.borrow_mut() = staged.then(|| dir.clone())); let options = PsdExportOptions { force_psb, stage_on_scratch_from: staged.then_some(0), ..Default::default() }; - let export = |ctl: &Interrupt| drop(document_to_psd_sized(&doc, &options, 0, ctl, PSD_MAX_FILE_SIZE)); + let export = |ctl: &Interrupt| drop(document_to_psd_sized(&doc, &options, 0, ctl, PSD_MAX_FILE_SIZE).unwrap()); let rows = doc.layers[0].surface().unwrap().content_bounds().height() as usize; assert_eq!(bands(&Interrupt::NONE, &export), rows, "{what}: one band a row"); assert_eq!(bands(&ctl, &export), 2, "{what}: stops at the band after the cancel"); diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 43b5a3f3f6..0c21f3ea19 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -380,7 +380,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr } else { doc }; - let (mut file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl)); + let (mut file, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psd_opts, ctl))?; // A cancelled conversion stops early with an incomplete model: never encode it. ctl.check().map_err(|_| IoError::Cancelled)?; warnings.extend(w); @@ -391,7 +391,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr let (layers, w) = match tiff_image_source(doc, &mut file, save_transparency && has_alpha).into_bytes(order) { Err(craft_psd::PsdError::LimitExceeded(_)) if !force_psb => { let psb_opts = PsdExportOptions { force_psb: true, ..psd_opts }; - let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl)); + let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl))?; ctl.check().map_err(|_| IoError::Cancelled)?; warnings.extend(w); warnings.push("layer data exceeds 4 GB; written with PSB-sized lengths, which some readers do not open".into()); diff --git a/crates/io/tests/it/deflate_compatibility.rs b/crates/io/tests/it/deflate_compatibility.rs index 16f066703d..a9fe9bd66a 100644 --- a/crates/io/tests/it/deflate_compatibility.rs +++ b/crates/io/tests/it/deflate_compatibility.rs @@ -71,10 +71,10 @@ fn png_psd_and_pcraft_decode_identically() { check_png(&photocraft_codecs::encode(&image, Format::Png, &Default::default()).unwrap(), &image); } let raw_opts = PsdExportOptions { merged_compression: Compression::Raw, merged_matte: false, ..Default::default() }; - let merged = document_to_psd_with(&doc, &raw_opts).0.image_data.data; + let merged = document_to_psd_with(&doc, &raw_opts).unwrap().0.image_data.data; for compression in [Compression::Zip, Compression::ZipPrediction] { let opts = PsdExportOptions { merged_compression: compression, merged_matte: false, ..Default::default() }; - let mut file = document_to_psd_with(&doc, &opts).0; + let mut file = document_to_psd_with(&doc, &opts).unwrap().0; // The IO exporter normally chooses Raw for float composites; also cover ZIP here. if depth == SampleType::F32 { file.image_data = craft_psd::ImageData::encode(compression, &merged, &file.header).unwrap(); diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index 4aa501133f..6402329d9d 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -325,7 +325,7 @@ fn document_to_psd_direct_api() { #[test] fn big_document_goes_psb_with_warning() { let d = photocraft_doc::Document::new("big", photocraft_geom::Size::new(30_001, 1), ColorMode::Grayscale, SampleType::U8); - let (f, w) = document_to_psd_with(&d, &PsdExportOptions::default()); + let (f, w) = document_to_psd_with(&d, &PsdExportOptions::default()).unwrap(); assert_eq!(f.header.version, craft_psd::Version::Psb); assert!(w.iter().any(|w| w.contains("PSB"))); } diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index e2e3a5b67a..28b61a147a 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -679,7 +679,7 @@ fn photoshop_transparency_and_spot_tiff(doc: &Document, layers: bool) -> Vec use craft_psd::{Compression, TaggedBlock}; let opts = PsdExportOptions { merged_matte: false, merged_compression: Compression::Raw, ..Default::default() }; - let (file, _) = document_to_psd_with(doc, &opts); + let (file, _) = document_to_psd_with(doc, &opts).unwrap(); let planes = file.decode_merged().unwrap(); let n = 16; assert_eq!(planes.len(), 5 * n); diff --git a/crates/io/tests/it/tiff_type_geometry.rs b/crates/io/tests/it/tiff_type_geometry.rs index ecf83065e0..2c2543a6d4 100644 --- a/crates/io/tests/it/tiff_type_geometry.rs +++ b/crates/io/tests/it/tiff_type_geometry.rs @@ -29,7 +29,7 @@ fn document_in(mode: ColorMode, depth: SampleType) -> Document { #[test] fn photoshop_mixed_order_tiff_import_keeps_editable_geometry_and_pixels() { let doc = document(); - let (psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()); + let (psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap(); let canonical = &psd.layers()[0].block(b"TySh").unwrap().data; let encoded = export(&doc, "test.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap(); let mut image = photocraft_codecs::decode(&encoded.bytes).unwrap(); @@ -64,7 +64,7 @@ fn layered_tiff_export_keeps_tysh_text_descriptor_big_endian() { (ColorMode::Cmyk, SampleType::U16), ] { let doc = document_in(mode, depth); - let (psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()); + let (psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap(); let canonical = &psd.layers()[0].block(b"TySh").unwrap().data; let encoded = export(&doc, "test.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap(); let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&encoded.bytes); @@ -98,7 +98,7 @@ fn layered_tiff_export_keeps_tysh_text_descriptor_big_endian() { fn foreign_or_unsafe_type_keeps_cached_pixels_without_editable_geometry() { let doc = document(); for foreign in [true, false] { - let (mut psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()); + let (mut psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap(); let block = psd.layer_info.as_mut().unwrap().layers[0].blocks.iter_mut().find(|b| b.key == *b"TySh").unwrap(); if foreign { // A foreign-order marker must be respected even if the descriptor could parse. @@ -119,7 +119,7 @@ fn foreign_or_unsafe_type_keeps_cached_pixels_without_editable_geometry() { #[test] fn canonical_type_the_typed_reader_rejects_stays_type_and_saves_its_block() { let doc = document(); - let (mut psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()); + let (mut psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default()).unwrap(); let block = psd.layer_info.as_mut().unwrap().layers[0].blocks.iter_mut().find(|b| b.key == *b"TySh").unwrap(); // A text descriptor version the typed reader doesn't know; the matrix is ordinary. block.data[52..56].copy_from_slice(&17u32.to_be_bytes()); @@ -129,6 +129,6 @@ fn canonical_type_the_typed_reader_rejects_stays_type_and_saves_its_block() { let LayerContent::Text(t) = &opened.layers[0].content else { panic!("canonical type must stay a type layer") }; let LayerContent::Text(before) = &doc.layers[0].content else { panic!("source type") }; assert_eq!(t.transform, before.transform); - let (saved, _) = document_to_psd_with(&opened, &PsdExportOptions::default()); + let (saved, _) = document_to_psd_with(&opened, &PsdExportOptions::default()).unwrap(); assert_eq!(saved.layers()[0].block(b"TySh").map(|b| &b.data), Some(&raw), "PSD save must keep the type block"); } From 14bcf7962e8ddc0af1d8768e2e5e784bcab39140 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 09:29:05 -0500 Subject: [PATCH 10/22] test(io): document bounded annotation smart-source fallback --- crates/io/tests/it/smart_contents_identity.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/io/tests/it/smart_contents_identity.rs b/crates/io/tests/it/smart_contents_identity.rs index c5dd8145d8..f819a91cae 100644 --- a/crates/io/tests/it/smart_contents_identity.rs +++ b/crates/io/tests/it/smart_contents_identity.rs @@ -349,3 +349,29 @@ fn plld_only_spilled_custom_warp_places_like_sold_and_round_trips_verbatim() { assert!(close(c.transform, t), "{:?} vs {t:?}", c.transform); assert_eq!(c.warp.as_ref(), Some(&warp)); } + +/// Shared annotation refusal preserves the established smart-source fallback policy: +/// the cached pixels survive and the warning explains loss of editable nested contents. +#[test] +fn oversized_nested_annotations_warn_before_smart_object_becomes_pixels() { + let mut source = Document::new("contents", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + source.notes = vec![photocraft_doc::Note::default(); 4097]; + let mut pixels = Surface::new(source.pixel_format()); + pixels.fill_rect(source.bounds(), &[1.0, 0.0, 0.0, 1.0]); + source.layers.push(Layer::new("red", LayerContent::Raster(pixels.clone()))); + let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap(); + let mut doc = Document::new("outer", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + let sm = SmartObject::new(SmartSource::Embedded { file_name: "contents.pcraft".into(), bytes: Arc::new(bytes) }, Affine::IDENTITY, Some(pixels)); + doc.layers.push(Layer::new("nested notes", LayerContent::Smart(sm))); + for extension in ["psd", "psb"] { + let out = export(&doc, extension, &Default::default()).unwrap(); + assert!( + out.warnings.iter().any(|w| w.contains("smart object written as pixels") && w.contains("annotations") && w.contains("annotation count")), + "{:?}", + out.warnings + ); + let back = import(extension, &out.bytes).unwrap().document; + assert!(matches!(back.layers[0].content, LayerContent::Raster(_))); + assert_eq!(back.layers[0].surface().unwrap().pixel(0, 0), vec![1.0, 0.0, 0.0, 1.0]); + } +} From 3f29649ff4c6a8ba0ce26260b56953d26ab756b0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:10:39 -0500 Subject: [PATCH 11/22] test(io): handle fallible palette PSD conversion results --- crates/io/src/palette_map.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index 0e30c2098a..bd769833a4 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -169,7 +169,7 @@ mod tests { } fn round_trip(doc: &Document) -> (PsdFile, Document) { - let (file, _) = document_to_psd(doc, false, None, None).unwrap(); + let (file, _) = document_to_psd(doc, false, None, None).unwrap().unwrap(); let bytes = file.to_bytes().unwrap(); let file = PsdFile::from_bytes(&bytes).unwrap(); let back = crate::import("test.psd", &bytes).unwrap().document; @@ -221,17 +221,17 @@ mod tests { assert_eq!(back.color_table, doc.color_table); for count in [0, 257] { doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0]; count], transparent: None }); - assert!(document_to_psd(&doc, false, None, None).is_none(), "{count}"); + assert!(document_to_psd(&doc, false, None, None).unwrap().is_none(), "{count}"); } doc.color_table = None; - assert!(document_to_psd(&doc, false, None, None).is_none()); + assert!(document_to_psd(&doc, false, None, None).unwrap().is_none()); } #[test] fn indexed_import_bounds_malformed_count_and_transparency_resources() { let mut doc = document(1, 1, SampleType::U8, ColorMode::Indexed, &[0.0, 0.0, 0.0, 1.0]); doc.color_table = Some(ColorTable { colors: vec![[0, 0, 0], [255, 255, 255]], transparent: None }); - let (original, _) = document_to_psd(&doc, false, None, None).unwrap(); + let (original, _) = document_to_psd(&doc, false, None, None).unwrap().unwrap(); for (count, expected) in [(vec![0, 0], 1), (vec![1, 1], 256), (vec![255, 255], 256), (vec![0], 256)] { let mut file = original.clone(); file.resources.retain(|r| r.id != COLOR_TABLE_COUNT); From edfdc633123e0ec1f8c17eed7cfe8edf1f25832e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:28:08 -0800 Subject: [PATCH 12/22] Keyboard Shortcuts test: add the action before assigning its key by index #11674 changed `assign_shortcut` to take the action's index in the Actions list instead of its name, while #14326's `an_action_function_key_is_no_edit` still passed "Sepia". The ui-egui lib tests on main no longer compile (E0308 at shortcut_set_switch_tests.rs:168). The test now adds a "Sepia" action and assigns F2 to index 0, as the shortcut_dispatch tests do. --- crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index dafa8be560..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,7 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From 3e0b20be316b04aef51202ff7e4d12057e3d2efc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:20:43 -0500 Subject: [PATCH 13/22] Use shared PSD guides resource decoder Retain PhotoCraft guide colour and resource retention policy. Shared implementation extracted from Bram Heerink original f49564d281bf8892db58ed154767717223aff4f6. --- Cargo.lock | 28 ++++++++++++++++------- crates/io/Cargo.toml | 1 + crates/io/src/guides_map.rs | 45 ++++--------------------------------- 3 files changed, 25 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..f7885c1078 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1628,6 +1628,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6d590ce432d9ae725590df72428aeb47256a01fd#6d590ce432d9ae725590df72428aeb47256a01fd" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-raw" version = "0.1.0" @@ -5527,7 +5538,7 @@ dependencies = [ "craft-ai-agents", "craft-flags", "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "getrandom 0.3.4", "hmac", "photocraft-color", @@ -5561,7 +5572,7 @@ dependencies = [ "clap_mangen", "craft-cms", "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "photocraft-automation", "photocraft-doc", "photocraft-engine", @@ -5626,7 +5637,7 @@ dependencies = [ "craft-image-codecs", "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3e970577b9bb446967c2003ec8ecaf4f28b0768c)", "craft-print", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "craft-xml", "exr", "flate2", @@ -5729,7 +5740,8 @@ dependencies = [ "craft-ora", "craft-pdf", "craft-pdn", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d590ce432d9ae725590df72428aeb47256a01fd)", "craft-svg", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", "craft-xcf", @@ -5859,9 +5871,9 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", - "craft-psd", + "craft-plist", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "flate2", "parley", "photocraft-color", @@ -5883,7 +5895,7 @@ dependencies = [ "craft-i18n", "craft-image-codecs", "craft-print", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "craft-ui", "craft-update", "eframe", @@ -5938,7 +5950,7 @@ name = "photocraft-web" version = "0.23.1" dependencies = [ "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "eframe", "egui", "js-sys", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 7280fa576e..ddbe19abdd 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -29,6 +29,7 @@ photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-algo = { workspace = true } craft-psd = { workspace = true } +craft-psd-guides = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6d590ce432d9ae725590df72428aeb47256a01fd" } photocraft-codecs = { workspace = true } photocraft-formats = { workspace = true } photocraft-raw = { workspace = true } diff --git a/crates/io/src/guides_map.rs b/crates/io/src/guides_map.rs index 6137011e2c..78038da666 100644 --- a/crates/io/src/guides_map.rs +++ b/crates/io/src/guides_map.rs @@ -18,50 +18,13 @@ use photocraft_doc::{Document, Guides}; -/// Grid and Guides, version 2 (positions, directions and colours). -pub const GUIDES_V2: u16 = 1092; -/// One GUID per guide, in 1092's order. -pub const GUIDE_IDS: u16 = 1097; -/// Photoshop's default guide colour (Cyan, `#4affff`), which 1092 also stores for guides -/// that use the preference colour. +pub use craft_psd_guides::guides::{GUIDE_IDS, GUIDES_V2, GuideV2, ids_count}; +/// Photoshop's default colour continues to follow the app preference. pub const DEFAULT_GUIDE_RGB: [u8; 3] = [0x4a, 0xff, 0xff]; -/// One guide of a 1092 resource. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct GuideV2 { - /// Position in 1/32 px. - pub location: i32, - pub vertical: bool, - pub rgb: [u8; 3], -} - -fn be_u32(data: &[u8], at: usize) -> Option { - let b = data.get(at..at.checked_add(4)?)?; - Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) -} - -/// The guides of a 1092 resource, or `None` when it is not version 2 or is cut short. +/// Decode the shared wire representation; document matching remains app policy. pub fn parse_v2(data: &[u8]) -> Option> { - if be_u32(data, 0)? != 2 { - return None; - } - let count = usize::try_from(be_u32(data, 12)?).ok()?; - // Each guide takes 9 bytes: a count the data can't hold is not a 1092 we understand. - if count > data.len().saturating_sub(16) / 9 { - return None; - } - (0..count) - .map(|i| { - let at = 16 + i * 9; - let g = data.get(at..at + 9)?; - Some(GuideV2 { location: i32::from_be_bytes([g[0], g[1], g[2], g[3]]), vertical: g[4] != 1, rgb: [g[6], g[7], g[8]] }) - }) - .collect() -} - -/// The number of entries a 1097 resource declares. -pub fn ids_count(data: &[u8]) -> Option { - be_u32(data, 0) + craft_psd_guides::guides::parse_v2(data).map(Iterator::collect) } /// The document's guides as 1092 would store them, sorted. From f3419cc57511fc78d7771be7b4fd714b52415aae Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:26:21 +0000 Subject: [PATCH 14/22] Keep text dependencies in canonical Cargo lock order --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From 607c8b9a62daec46510fd3fd423544075bd977aa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:36:05 -0500 Subject: [PATCH 15/22] Use shared PSD Duotone record parsing and assembly Preserve Gert Pellin and David Mann original document colour, curve and fallback policy; compare output against frozen original writer. --- Cargo.lock | 28 +++++--- crates/io/Cargo.toml | 1 + crates/io/src/duotone_map.rs | 133 ++++++++++++++++++++--------------- 3 files changed, 99 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..f9f0bd3e9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1628,6 +1628,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f#b9c22554ce0fd2caccdb53b417082a2ff2ef178f" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-raw" version = "0.1.0" @@ -5527,7 +5538,7 @@ dependencies = [ "craft-ai-agents", "craft-flags", "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "getrandom 0.3.4", "hmac", "photocraft-color", @@ -5561,7 +5572,7 @@ dependencies = [ "clap_mangen", "craft-cms", "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "photocraft-automation", "photocraft-doc", "photocraft-engine", @@ -5626,7 +5637,7 @@ dependencies = [ "craft-image-codecs", "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3e970577b9bb446967c2003ec8ecaf4f28b0768c)", "craft-print", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "craft-xml", "exr", "flate2", @@ -5729,7 +5740,8 @@ dependencies = [ "craft-ora", "craft-pdf", "craft-pdn", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b9c22554ce0fd2caccdb53b417082a2ff2ef178f)", "craft-svg", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", "craft-xcf", @@ -5859,9 +5871,9 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", - "craft-psd", + "craft-plist", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "flate2", "parley", "photocraft-color", @@ -5883,7 +5895,7 @@ dependencies = [ "craft-i18n", "craft-image-codecs", "craft-print", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "craft-ui", "craft-update", "eframe", @@ -5938,7 +5950,7 @@ name = "photocraft-web" version = "0.23.1" dependencies = [ "craft-image-codecs", - "craft-psd", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", "eframe", "egui", "js-sys", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 7280fa576e..1aa41defd1 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -29,6 +29,7 @@ photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-algo = { workspace = true } craft-psd = { workspace = true } +craft-psd-duotone = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b9c22554ce0fd2caccdb53b417082a2ff2ef178f" } photocraft-codecs = { workspace = true } photocraft-formats = { workspace = true } photocraft-raw = { workspace = true } diff --git a/crates/io/src/duotone_map.rs b/crates/io/src/duotone_map.rs index 77d60b249f..8a8ee3d258 100644 --- a/crates/io/src/duotone_map.rs +++ b/crates/io/src/duotone_map.rs @@ -25,27 +25,16 @@ use craft_psd::aco::AcoColor; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{Duotone, DuotoneInk}; -/// Length of the block Photoshop writes. -pub(crate) const BLOCK_LEN: usize = 524; -/// Gray densities (%) of a curve's 13 points. +use craft_psd_duotone::duotone as wire; +#[cfg(test)] +const BLOCK_LEN: usize = wire::BLOCK_LEN; const CURVE_AT: [u16; 13] = [0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]; +#[cfg(test)] const NO_COLOR: [u8; 10] = [0xFF, 0xFF, 0, 0, 0, 0, 0, 0, 0, 0]; -const NAMES_AT: usize = 44; -const CURVES_AT: usize = 300; -const DOT_GAIN_AT: usize = 412; -/// Image resource: the inks' Lab equivalents. -pub(crate) const ALTERNATE_DUOTONE_COLORS: u16 = 1066; +pub(crate) const ALTERNATE_DUOTONE_COLORS: u16 = wire::ALTERNATE_DUOTONE_COLORS; -fn u16_at(b: &[u8], at: usize) -> Option { - b.get(at..at + 2).map(|s| u16::from_be_bytes([s[0], s[1]])) -} - -/// The sRGB display colour of the 10-byte colour structure at `at`; `None` for a colour book or -/// another space we can't show. -fn display(b: &[u8], at: usize) -> Option<[f32; 3]> { - let space = u16_at(b, at)?; - let values = [u16_at(b, at + 2)?, u16_at(b, at + 4)?, u16_at(b, at + 6)?, u16_at(b, at + 8)?]; - let c = crate::channel_map::decode_known_color(space, values)?; +fn display([space, a, b, c, d]: wire::ColorRecord) -> Option<[f32; 3]> { + let c = crate::channel_map::decode_known_color(space, [a, b, c, d])?; Some(c.to_rgb().map(|v| v.clamp(0.0, 1.0))) } @@ -54,27 +43,19 @@ fn display(b: &[u8], at: usize) -> Option<[f32; 3]> { /// an ink's colour can't be shown even so; it is then black here, and the caller shows the /// grey plate instead. pub(crate) fn parse(b: &[u8], alternate: Option<&[u8]>, unknown: &mut bool) -> Option> { - if b.len() < DOT_GAIN_AT || u16_at(b, 0)? != 1 { - return None; - } - let n = usize::from(u16_at(b, 2)?); - if !(1..=4).contains(&n) { - return None; - } - (0..n) + let view = wire::DuotoneView::parse(b)?; + (0..view.ink_count()) .map(|i| { - let alt = alternate.filter(|a| u16_at(a, 0) == Some(1) && u16_at(a, 2).is_some_and(|k| usize::from(k) > i)); - let color = display(b, 4 + 10 * i).or_else(|| display(alt?, 4 + 10 * i)).unwrap_or_else(|| { + let raw = view.ink(i)?; + let color = display(raw.color).or_else(|| display(wire::alternate_color(alternate?, i)?)).unwrap_or_else(|| { *unknown = true; [0.0; 3] }); - let name_at = NAMES_AT + 64 * i; - let len = usize::from(*b.get(name_at)?).min(63); - let name = String::from_utf8_lossy(b.get(name_at + 1..name_at + 1 + len)?).into_owned(); - let curve_at = CURVES_AT + 28 * i; + let len = usize::from(raw.name[0]).min(63); + let name = String::from_utf8_lossy(&raw.name[1..1 + len]).into_owned(); let mut curve: Vec = Vec::new(); for (k, x) in CURVE_AT.iter().enumerate() { - let v = u16_at(b, curve_at + 2 * k)? as i16; + let v = raw.curve[k]; if v >= 0 { curve.push(CurvePoint { input: f32::from(*x) / 100.0, output: (f32::from(v) / 1000.0).clamp(0.0, 1.0) }); } @@ -91,40 +72,35 @@ pub(crate) fn parse(b: &[u8], alternate: Option<&[u8]>, unknown: &mut bool) -> O /// sampled at the 13 gray densities (the points on that grid as they are, the others left out), /// Photoshop's default dot gain and computed overprint colours. pub(crate) fn write(d: &Duotone) -> Vec { - let mut b = Vec::with_capacity(BLOCK_LEN); + use wire::{InkCount, InkRecord}; let inks: Vec<&DuotoneInk> = d.inks.iter().take(4).collect(); - b.extend_from_slice(&1u16.to_be_bytes()); - b.extend_from_slice(&(inks.len().max(1) as u16).to_be_bytes()); - for i in 0..4 { - match inks.get(i) { + let count = match inks.len() { + 0 | 1 => InkCount::One, + 2 => InkCount::Two, + 3 => InkCount::Three, + _ => InkCount::Four, + }; + let slots = std::array::from_fn(|i| { + let color = match inks.get(i) { Some(ink) => { let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let (space, v) = AcoColor::Rgb(ink.color.map(q)).to_record(); - b.extend_from_slice(&space.to_be_bytes()); - v.iter().for_each(|x| b.extend_from_slice(&x.to_be_bytes())); + [space, v[0], v[1], v[2], v[3]] } - None => b.extend_from_slice(&NO_COLOR), - } - } - for i in 0..4 { + None => wire::NO_COLOR, + }; let mut name = [0u8; 64]; if let Some(ink) = inks.get(i) { let bytes: Vec = ink.name.chars().map(|c| if c.is_ascii() { c as u8 } else { b'?' }).take(63).collect(); name[0] = bytes.len() as u8; name[1..=bytes.len()].copy_from_slice(&bytes); } - b.extend_from_slice(&name); - } - for i in 0..4 { let values = curve_values(inks.get(i).map(|ink| ink.curve.as_slice())); - values.iter().for_each(|v| b.extend_from_slice(&v.to_be_bytes())); - b.extend_from_slice(&0i16.to_be_bytes()); - } - b.extend_from_slice(&20u16.to_be_bytes()); - for _ in 0..11 { - b.extend_from_slice(&NO_COLOR); - } - b + let mut curve = [0i16; 14]; + curve[..13].copy_from_slice(&values); + InkRecord { color, name, curve } + }); + wire::write_block(count, &slots, 20, &[wire::NO_COLOR; 11]).to_vec() } /// A curve's 13 values: an identity curve (or none) is 0 and 100 % only, as Photoshop writes it; @@ -166,6 +142,53 @@ fn curve_values(curve: Option<&[CurvePoint]>) -> [i16; 13] { #[cfg(test)] mod tests { use super::*; + fn original_write(d: &Duotone) -> Vec { + let mut b = Vec::with_capacity(BLOCK_LEN); + let inks: Vec<&DuotoneInk> = d.inks.iter().take(4).collect(); + b.extend_from_slice(&1u16.to_be_bytes()); + b.extend_from_slice(&(inks.len().max(1) as u16).to_be_bytes()); + for i in 0..4 { + match inks.get(i) { + Some(ink) => { + let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; + let (space, v) = AcoColor::Rgb(ink.color.map(q)).to_record(); + b.extend_from_slice(&space.to_be_bytes()); + v.iter().for_each(|x| b.extend_from_slice(&x.to_be_bytes())); + } + None => b.extend_from_slice(&NO_COLOR), + } + } + for i in 0..4 { + let mut name = [0u8; 64]; + if let Some(ink) = inks.get(i) { + let bytes: Vec = ink.name.chars().map(|c| if c.is_ascii() { c as u8 } else { b'?' }).take(63).collect(); + name[0] = bytes.len() as u8; + name[1..=bytes.len()].copy_from_slice(&bytes); + } + b.extend_from_slice(&name); + } + for i in 0..4 { + let values = curve_values(inks.get(i).map(|ink| ink.curve.as_slice())); + values.iter().for_each(|v| b.extend_from_slice(&v.to_be_bytes())); + b.extend_from_slice(&0i16.to_be_bytes()); + } + b.extend_from_slice(&20u16.to_be_bytes()); + for _ in 0..11 { + b.extend_from_slice(&NO_COLOR); + } + b + } + + #[test] + fn shared_writer_matches_original_for_all_counts_and_name_policies() { + for n in 0..=6 { + let d = Duotone { + inks: (0..n).map(|i| ink(&format!("inkΓ©{i}{}", "x".repeat(70)), [0.1, 0.5, 0.9], &[(0.0, 0.2), (0.35, 0.6), (1.0, 0.8)])).collect(), + psd_raw: None, + }; + assert_eq!(write(&d), original_write(&d)); + } + } fn ink(name: &str, color: [f32; 3], curve: &[(f32, f32)]) -> DuotoneInk { let curve = From 24550340c2eafe62c6dfa0c6fcb8c690364ff063 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:28:08 -0800 Subject: [PATCH 16/22] Keyboard Shortcuts test: add the action before assigning its key by index #11674 changed `assign_shortcut` to take the action's index in the Actions list instead of its name, while #14326's `an_action_function_key_is_no_edit` still passed "Sepia". The ui-egui lib tests on main no longer compile (E0308 at shortcut_set_switch_tests.rs:168). The test now adds a "Sepia" action and assigns F2 to index 0, as the shortcut_dispatch tests do. --- crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index dafa8be560..68a82501d9 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,7 +165,8 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + h.state_mut().session.actions.list.push(photocraft_engine::actions_cmds::Action::new("Sepia", Vec::new())); + crate::actions::assign_shortcut(h.state_mut(), 0, "F2").unwrap(); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); From f8b8243ce90d443f951614793c9e210db89baf79 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 19:48:25 +0100 Subject: [PATCH 17/22] Cargo.lock: sort photocraft-text's dependencies the way cargo writes them The gate's `git diff --exit-code -- Cargo.lock` step fails on main because craft-plist sits before base64 in photocraft-text's list; cargo re-sorts it on every build. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..03aadc6d20 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", From e879da042c8608c36b4dcf4b92a1dec438ba3aa0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:22:37 -0500 Subject: [PATCH 18/22] fix: preserve bounded annotation text and unchanged legacy bytes --- crates/io/src/annotation_shared_tests.rs | 31 ++++++++++++++++++++++++ crates/io/src/annotations_map.rs | 26 +++++++++++++++++--- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/io/src/annotation_shared_tests.rs b/crates/io/src/annotation_shared_tests.rs index dd77d18e06..d4f6ad69bf 100644 --- a/crates/io/src/annotation_shared_tests.rs +++ b/crates/io/src/annotation_shared_tests.rs @@ -90,3 +90,34 @@ fn text_cannot_cross_declared_record_boundary() { block[8..12].copy_from_slice(&(length - 2).to_be_bytes()); assert!(parse_entries(&block).is_none()); } + +#[test] +fn normalized_utf16_budget_counts_units_not_utf8_bytes() { + assert_eq!(text_bytes("βœ“βœ“βœ“", 8), Some(8)); + assert_eq!(text_bytes("π„ž", 6), Some(6)); + assert_eq!(text_bytes("a\r\nb\nc\r", 14), Some(14)); + assert_eq!(text_bytes("βœ“βœ“βœ“", 7), None); + assert_eq!(text_bytes("π„ž", 5), None); + let note = Note { text: "βœ“".repeat(3 * 1024 * 1024), ..Default::default() }; + assert!(write_anno(&[note], &[]).is_ok()); +} + +#[test] +fn unchanged_legacy_text_keeps_raw_bytes_without_utf16_rewrite() { + let mut block = legacy_anno(&[Note { text: "x".into(), ..Default::default() }], &[]); + let key = block.windows(4).position(|w| w == b"txtC").unwrap(); + block.truncate(key + 8); + block.extend(std::iter::repeat_n(b'x', 9 * 1024 * 1024)); + let size = u32::try_from(block.len() - key - 8).unwrap(); + block[key + 4..key + 8].copy_from_slice(&size.to_be_bytes()); + block[key - 4..key].copy_from_slice(&(size + 12).to_be_bytes()); + let record = u32::try_from(block.len() - 8).unwrap(); + block[8..12].copy_from_slice(&record.to_be_bytes()); + let mut doc = Document::new("notes", photocraft_doc::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + doc.notes = parse_anno(&block).unwrap(); + assert!(write_anno(&doc.notes, &[]).is_err()); + let blocks = vec![(*b"8BIM", ANNO, Arc::new(block))]; + assert_eq!(export_blocks(&doc, blocks.clone()).unwrap(), blocks); + doc.notes[0].text.push('x'); + assert!(export_blocks(&doc, blocks).is_err()); +} diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index acc802fa60..b56961723c 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -74,10 +74,25 @@ fn decode_text(data: &[u8]) -> String { s.trim_end_matches('\0').replace("\r\n", "\n").replace('\r', "\n") } +fn normalized_text(s: &str) -> impl Iterator + '_ { + let mut previous_cr = false; + s.chars().filter_map(move |c| { + let skip = previous_cr && c == '\n'; + previous_cr = c == '\r'; + if skip { None } else { Some(if c == '\n' { '\r' } else { c }) } + }) +} + +fn text_bytes(s: &str, limit: usize) -> Option { + normalized_text(s).try_fold(2usize, |bytes, c| bytes.checked_add(c.len_utf16() * 2).filter(|&n| n <= limit)) +} + fn encode_text(s: &str) -> Vec { let mut out = vec![0xFE, 0xFF]; - for u in s.replace("\r\n", "\n").replace('\n', "\r").encode_utf16() { - out.extend_from_slice(&u.to_be_bytes()); + for c in normalized_text(s) { + for u in c.encode_utf16(&mut [0; 2]) { + out.extend_from_slice(&u.to_be_bytes()); + } } out } @@ -117,7 +132,7 @@ pub fn parse_anno(data: &[u8]) -> Option> { fn write_note(n: &Note) -> craft_psd::Result> { let limits = craft_psd::annotations::Limits::default(); // Bound temporary text normalization before the shared fallible writer allocates. - if n.text.len().checked_mul(2).and_then(|n| n.checked_add(2)).is_none_or(|n| n > limits.bytes) { + if text_bytes(&n.text, limits.bytes).is_none() { return Err(craft_psd::PsdError::LimitExceeded("annotation text")); } let (x, y) = (n.position[0].round() as i32, n.position[1].round() as i32); @@ -188,6 +203,11 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec> = entries.as_ref().map(|e| e.iter().filter_map(|e| if let Entry::Text(n) = e { Some(n.clone()) } else { None }).collect()); + // Unedited decoded notes retain the original bounded block, even when its legacy + // single-byte text would exceed the UTF-16 writer budget after conversion. + if parsed.as_deref() == Some(doc.notes.as_slice()) || (entries.is_none() && doc.notes.is_empty()) { + return Ok(blocks); + } // Compare in stored precision (colours are 16-bit, positions whole pixels, empty popups get a // default rectangle). let want = parse_anno(&write_anno(&doc.notes, &[]).map_err(|e| crate::IoError::Unsupported(e.to_string()))?); From 463baf8d33c4e68f0c35494667171e0d92b432dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:41:22 -0500 Subject: [PATCH 19/22] deps: bump tar, zip, roxmltree, rustls-webpki and symphonia to their latest versions (#15209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `roxmltree`: 0.20.0, 0.21.1 β†’ 0.20.0, 0.21.2 - `rustls-webpki`: 0.103.15 β†’ 0.103.16 - `zip`: 9.1.0 β†’ 9.1.3 Lockfile only. --- Cargo.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d3935c94a4..d952410292 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5859,8 +5859,8 @@ dependencies = [ name = "photocraft-text" version = "0.23.1" dependencies = [ - "craft-plist", "base64 0.23.1", + "craft-plist", "craft-psd", "flate2", "parley", @@ -7005,9 +7005,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -10084,9 +10084,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.1.0" +version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "1156b39d142a34b999c2310a50455e0cb3760bf7efad0122f796d813bee26ccb" dependencies = [ "crc32fast", "flate2", From 2d74ae4aaba702b6435a10420ee5966249d6e4fe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:14:57 -0500 Subject: [PATCH 20/22] io: retain note popup normalization and target layered TIFF tests --- crates/io/src/annotation_shared_tests.rs | 11 +++++++++-- crates/io/src/annotations_map.rs | 5 +++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/io/src/annotation_shared_tests.rs b/crates/io/src/annotation_shared_tests.rs index d4f6ad69bf..6b68b9fe7c 100644 --- a/crates/io/src/annotation_shared_tests.rs +++ b/crates/io/src/annotation_shared_tests.rs @@ -67,7 +67,7 @@ fn shared_writer_matches_valid_legacy_bytes() { for x in [0.0, -5.5, f64::from(i32::MAX), f64::INFINITY] { let note = Note { text: text.into(), author: "Γ€βœ“".repeat(180), modified: "date".into(), position: [x, 2.5], ..Default::default() }; let extra = vec![vec![0, 0, 0, 8, b's', b'n', b'd', b'A']]; - assert_eq!(write_anno(&[note.clone()], &extra).unwrap(), legacy_anno(&[note], &extra)); + assert_eq!(write_anno(std::slice::from_ref(¬e), &extra).unwrap(), legacy_anno(&[note], &extra)); } } } @@ -80,7 +80,14 @@ fn every_export_path_refuses_excess_notes() { assert!(crate::document_to_psd(&d).is_err()); assert!(crate::document_to_psd_with(&d, &Default::default()).is_err()); assert!(crate::encode_with(&d, "psd", &Default::default(), &photocraft_raster::Interrupt::NONE).is_err()); - assert!(crate::encode_with(&d, "tiff", &Default::default(), &photocraft_raster::Interrupt::NONE).is_err()); + // Flat TIFF intentionally does not encode annotations. Exercise the actual layered + // Photoshop-data path; Multichannel has no TIFF layer representation. + if mode != photocraft_doc::ColorMode::Multichannel { + d.layers.push(photocraft_doc::Layer::raster("notes layer", d.pixel_format())); + let opts = crate::ExportOptions { tiff_layers: true, ..Default::default() }; + assert!(crate::tiff_layers::would_write_layers(&d)); + assert!(crate::encode_with(&d, "tiff", &opts, &photocraft_raster::Interrupt::NONE).is_err()); + } } } #[test] diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index b56961723c..4665042322 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -204,8 +204,9 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec> = entries.as_ref().map(|e| e.iter().filter_map(|e| if let Entry::Text(n) = e { Some(n.clone()) } else { None }).collect()); // Unedited decoded notes retain the original bounded block, even when its legacy - // single-byte text would exceed the UTF-16 writer budget after conversion. - if parsed.as_deref() == Some(doc.notes.as_slice()) || (entries.is_none() && doc.notes.is_empty()) { + // single-byte text would exceed the UTF-16 writer budget after conversion. An all-zero + // popup still needs the established default-rectangle normalization on save (#939). + if (parsed.as_deref() == Some(doc.notes.as_slice()) && doc.notes.iter().all(|n| n.popup != [0.0; 4])) || (entries.is_none() && doc.notes.is_empty()) { return Ok(blocks); } // Compare in stored precision (colours are 16-bit, positions whole pixels, empty popups get a From 07eeaf8e94af91a16c35cc550765f6986740aae7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:39:38 -0500 Subject: [PATCH 21/22] Use shared PSD alpha-channel identifier writer Reuse the byte-identical resource 1053 implementation already pinned in craft-psd. Retain existing app ordering policy, callers and byte regression tests; no dependency changes. Co-authored-by: Jason D --- crates/io/src/channel_map.rs | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/crates/io/src/channel_map.rs b/crates/io/src/channel_map.rs index cf99d28a66..95296a69d9 100644 --- a/crates/io/src/channel_map.rs +++ b/crates/io/src/channel_map.rs @@ -41,17 +41,7 @@ pub(crate) fn photoshop_spot_plane(plane: &mut [u8], sample: SampleType) { /// new document's channels 3, 4, 5, … in every colour mode (RGB, CMYK, Gray and Lab, in its PSDs /// and TIFFs alike), so these do too. `transparency`: the merged image's transparency channel /// comes first, with identifier 0 (Photoshop's transparent PSD lists `0, 3, 4, 5`). -pub(crate) fn alpha_identifiers(transparency: bool, count: usize) -> Vec { - let mut out = Vec::with_capacity(count.saturating_add(1).saturating_mul(4)); - if transparency { - out.extend_from_slice(&0u32.to_be_bytes()); - } - for i in 0..count { - let id = 3u32.saturating_add(u32::try_from(i).unwrap_or(u32::MAX)); - out.extend_from_slice(&id.to_be_bytes()); - } - out -} +pub(crate) use craft_psd::tiff::layered::alpha_identifiers; /// Resource 1077 for `channels` (in file order): a version, then 13 bytes per channel (colour /// space, four components, opacity, kind). Every corpus file, Photoshop's included, uses 13; From c1fa809f74adc4f0b646289c2f048cfcf32f47a0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:51:07 -0500 Subject: [PATCH 22/22] Pin shared PSD guides to its merged prerequisite --- Cargo.lock | 4 ++-- crates/io/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b99f7398b9..da2c948e15 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1631,7 +1631,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6d590ce432d9ae725590df72428aeb47256a01fd#6d590ce432d9ae725590df72428aeb47256a01fd" +source = "git+https://github.com/storytold/craft-libs?rev=589842f0da5c5a11e71f39b70092dcb918b92f39#589842f0da5c5a11e71f39b70092dcb918b92f39" dependencies = [ "encoding_rs", "flate2", @@ -5741,7 +5741,7 @@ dependencies = [ "craft-pdf", "craft-pdn", "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda)", - "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d590ce432d9ae725590df72428aeb47256a01fd)", + "craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=589842f0da5c5a11e71f39b70092dcb918b92f39)", "craft-svg", "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)", "craft-xcf", diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index ddbe19abdd..1ed14763db 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -29,7 +29,7 @@ photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-algo = { workspace = true } craft-psd = { workspace = true } -craft-psd-guides = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6d590ce432d9ae725590df72428aeb47256a01fd" } +craft-psd-guides = { package = "craft-psd", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "589842f0da5c5a11e71f39b70092dcb918b92f39" } photocraft-codecs = { workspace = true } photocraft-formats = { workspace = true } photocraft-raw = { workspace = true }