mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge main into codex/raw-adapter-safety
Keep main's newer craft-psd (2284a6bf) and craft-cms (c6eb84d4) pins; keep this branch's unified fe6b443a pins elsewhere (newer than main's ad8faa1c). Cargo.lock regenerated from main's lock.
This commit is contained in:
commit
e8531bbfd9
28 files changed
+673
-368
No files matched your search
Generated
+33
-9
@@ -1352,7 +1352,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=fe6b443acf3eccaf514064812e6e6bf24257652a#fe6b443acf3eccaf514064812e6e6bf24257652a"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c6eb84d427d81b6d64207654c8ee0516cd3d7324#c6eb84d427d81b6d64207654c8ee0516cd3d7324"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1621,7 +1621,29 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=09188c3bbfa443b089a3e022fad6abd7b464efda#09188c3bbfa443b089a3e022fad6abd7b464efda"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f#2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=589842f0da5c5a11e71f39b70092dcb918b92f39#589842f0da5c5a11e71f39b70092dcb918b92f39"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"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",
|
||||
@@ -5529,7 +5551,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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"photocraft-color",
|
||||
@@ -5563,7 +5585,7 @@ dependencies = [
|
||||
"clap_mangen",
|
||||
"craft-cms",
|
||||
"craft-image-codecs",
|
||||
"craft-psd",
|
||||
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"photocraft-automation",
|
||||
"photocraft-doc",
|
||||
"photocraft-engine",
|
||||
@@ -5628,7 +5650,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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"craft-xml",
|
||||
"exr",
|
||||
"flate2",
|
||||
@@ -5731,7 +5753,9 @@ dependencies = [
|
||||
"craft-ora",
|
||||
"craft-pdf",
|
||||
"craft-pdn",
|
||||
"craft-psd",
|
||||
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=589842f0da5c5a11e71f39b70092dcb918b92f39)",
|
||||
"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=fe6b443acf3eccaf514064812e6e6bf24257652a)",
|
||||
"craft-xcf",
|
||||
@@ -5863,7 +5887,7 @@ version = "0.23.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-plist",
|
||||
"craft-psd",
|
||||
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"flate2",
|
||||
"parley",
|
||||
"photocraft-color",
|
||||
@@ -5885,7 +5909,7 @@ dependencies = [
|
||||
"craft-i18n",
|
||||
"craft-image-codecs",
|
||||
"craft-print",
|
||||
"craft-psd",
|
||||
"craft-psd 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
"eframe",
|
||||
@@ -5940,7 +5964,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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
|
||||
"eframe",
|
||||
"egui",
|
||||
"js-sys",
|
||||
|
||||
+2
-2
@@ -24,7 +24,7 @@ photocraft-raster = { path = "crates/raster" }
|
||||
photocraft-doc = { path = "crates/doc" }
|
||||
photocraft-ops = { path = "crates/ops" }
|
||||
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "e2e3b4213afb2b5e7651bc1b1a1cf72a8bb6313d" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "09188c3bbfa443b089a3e022fad6abd7b464efda" }
|
||||
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 = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
|
||||
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
|
||||
photocraft-raw = { path = "crates/raw" }
|
||||
@@ -47,7 +47,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 = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c6eb84d427d81b6d64207654c8ee0516cd3d7324" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
|
||||
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "fe6b443acf3eccaf514064812e6e6bf24257652a" }
|
||||
|
||||
@@ -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");
|
||||
@@ -12,12 +13,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();
|
||||
|
||||
@@ -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");
|
||||
@@ -11,12 +12,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();
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! 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", 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"];
|
||||
|
||||
/// 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();
|
||||
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> {
|
||||
/// 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");
|
||||
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 }
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]])
|
||||
}
|
||||
@@ -178,28 +178,12 @@ 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
|
||||
// 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.
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -170,13 +170,27 @@ fn list_system_printers(s: &Session) -> Vec<craft_print::Printer> {
|
||||
Some(source) => source(),
|
||||
None => {
|
||||
SYSTEM_LISTINGS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
craft_print::printers()
|
||||
system_printers_now()
|
||||
}
|
||||
};
|
||||
keep(&LAST_PRINTERS, s.printer_source.as_ref(), list.clone());
|
||||
list
|
||||
}
|
||||
|
||||
/// The system's printers. craft-print asks each Windows driver about two-sided printing through
|
||||
/// prntvpt.dll; without it, list the spooler's printers through GDI instead (#8272). Like
|
||||
/// `craft_print::printers`, a listing that fails is an empty list.
|
||||
fn system_printers_now() -> Vec<craft_print::Printer> {
|
||||
if require_print_tickets().is_ok() {
|
||||
return craft_print::printers();
|
||||
}
|
||||
craft_print::rgb::printers()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|p| craft_print::Printer { name: p.name, description: String::new(), default: p.default, two_sided: None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `file.printers`' stand-in: the session's outside the browser, and `None` in the browser, where
|
||||
/// `file.printers` lists no printers.
|
||||
fn stand_in_printers(source: Option<&PrinterSource>, browser: bool) -> Option<&PrinterSource> {
|
||||
@@ -1067,6 +1081,8 @@ fn driver_printable(p: &Value) -> Option<Value> {
|
||||
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<Value> {
|
||||
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));
|
||||
@@ -1143,31 +1159,67 @@ 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))) {
|
||||
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_windows_pdf_at(&system_root())?;
|
||||
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")]
|
||||
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.",
|
||||
));
|
||||
}
|
||||
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";
|
||||
|
||||
/// The running Windows directory (`%SystemRoot%`), `C:\Windows` if the variable is unset.
|
||||
#[cfg(target_os = "windows")]
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
|
||||
|
||||
@@ -1310,28 +1310,44 @@ 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_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() {
|
||||
let system_dll_loads = |name| dll_loads(&system_dll(&system_root(), name));
|
||||
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");
|
||||
}
|
||||
// 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() {
|
||||
assert!(require_windows_pdf().is_ok());
|
||||
assert!(require_print_tickets().is_ok());
|
||||
}
|
||||
|
||||
/// A 500 × 1000 pt document (72 ppi) on A3 (841.89 × 1190.55 pt): its height sets the fit.
|
||||
|
||||
@@ -29,6 +29,8 @@ 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" }
|
||||
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 }
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Frozen valid-wire writer oracle from PhotoCraft5bdbcc118.
|
||||
//! Original wire writer Brandon Thomas aa87012a; saturating icon fix wstock0d6e58e2.
|
||||
use super::*;
|
||||
fn pascal(out: &mut Vec<u8>, s: &str) {
|
||||
let bytes: Vec<u8> = 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<u8> {
|
||||
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<u8>]) -> Vec<u8> {
|
||||
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
|
||||
}
|
||||
|
||||
#[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(std::slice::from_ref(¬e), &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());
|
||||
// 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]
|
||||
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());
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
+109
-140
@@ -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<u8> {
|
||||
self.take(1).map(|b| b[0])
|
||||
}
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
fn i32(&mut self) -> Option<i32> {
|
||||
self.u32().map(|v| v as i32)
|
||||
}
|
||||
fn pascal(&mut self) -> Option<String> {
|
||||
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<u8>, s: &str) {
|
||||
let bytes: Vec<u8> = 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<u8> {
|
||||
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.
|
||||
@@ -112,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<Item = char> + '_ {
|
||||
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<usize> {
|
||||
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<u8> {
|
||||
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
|
||||
}
|
||||
@@ -127,51 +104,24 @@ enum Entry {
|
||||
}
|
||||
|
||||
fn parse_entries(data: &[u8]) -> Option<Vec<Entry>> {
|
||||
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 +129,60 @@ pub fn parse_anno(data: &[u8]) -> Option<Vec<Note>> {
|
||||
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<u8> {
|
||||
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<Vec<u8>> {
|
||||
let limits = craft_psd::annotations::Limits::default();
|
||||
// Bound temporary text normalization before the shared fallible writer allocates.
|
||||
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);
|
||||
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<u8>]) -> Vec<u8> {
|
||||
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<u8>]) -> craft_psd::Result<Vec<u8>> {
|
||||
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 +198,20 @@ 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<photocraft_doc::PsdGlobalBlock>) -> Vec<photocraft_doc::PsdGlobalBlock> {
|
||||
pub fn export_blocks(doc: &Document, mut blocks: Vec<photocraft_doc::PsdGlobalBlock>) -> Result<Vec<photocraft_doc::PsdGlobalBlock>, 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<Vec<Note>> = 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. 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
|
||||
// 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 +222,14 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec<photocraft_doc::PsdGlobalBl
|
||||
// With no notes, a block we can't read is kept as is: it isn't "the last note deleted", and
|
||||
// dropping it would delete the annotations it holds (issue #944).
|
||||
if parsed.as_deref().zip(want.as_deref()).is_some_and(|(p, w)| same(p, w)) || (entries.is_none() && doc.notes.is_empty()) {
|
||||
return blocks;
|
||||
return Ok(blocks);
|
||||
}
|
||||
let extra: Vec<Vec<u8>> = 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 +238,7 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec<photocraft_doc::PsdGlobalBl
|
||||
(None, Some(f)) => blocks.push((*b"8BIM", ANNO, f)),
|
||||
(None, None) => {}
|
||||
}
|
||||
blocks
|
||||
Ok(blocks)
|
||||
}
|
||||
|
||||
fn num(v: &Value) -> Option<f64> {
|
||||
@@ -488,7 +453,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 +462,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 +482,12 @@ mod tests {
|
||||
let bad: Vec<photocraft_doc::PsdGlobalBlock> = 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 +527,7 @@ mod tests {
|
||||
assert!(!keep_resource(&d, COUNT_INFO));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "annotation_shared_tests.rs"]
|
||||
mod shared_tests;
|
||||
@@ -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<u8> {
|
||||
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;
|
||||
|
||||
@@ -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<u16> {
|
||||
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<Vec<DuotoneInk>> {
|
||||
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<CurvePoint> = 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<u8> {
|
||||
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<u8> = 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<u8> {
|
||||
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<u8> = 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 =
|
||||
|
||||
@@ -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<u32> {
|
||||
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<Vec<GuideV2>> {
|
||||
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<u32> {
|
||||
be_u32(data, 0)
|
||||
craft_psd_guides::guides::parse_v2(data).map(Iterator::collect)
|
||||
}
|
||||
|
||||
/// The document's guides as 1092 would store them, sorted.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -102,7 +102,7 @@ pub(crate) fn document_to_psd(
|
||||
force_psb: bool,
|
||||
size_limit: Option<u64>,
|
||||
patterns: Option<&[photocraft_doc::PsdGlobalBlock]>,
|
||||
) -> (PsdFile, Vec<String>) {
|
||||
) -> Result<(PsdFile, Vec<String>), 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<u64>,
|
||||
warnings: &mut Vec<String>,
|
||||
patterns: Option<&[photocraft_doc::PsdGlobalBlock]>,
|
||||
) -> PsdFile {
|
||||
) -> Result<PsdFile, crate::IoError> {
|
||||
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<TaggedBlock> = crate::annotations_map::export_blocks(doc, patterns)
|
||||
let global_blocks: Vec<TaggedBlock> = 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)]
|
||||
|
||||
@@ -28,18 +28,20 @@ pub(crate) fn document_to_psd(
|
||||
force_psb: bool,
|
||||
size_limit: Option<u64>,
|
||||
patterns: Option<&[photocraft_doc::PsdGlobalBlock]>,
|
||||
) -> Option<(PsdFile, Vec<String>)> {
|
||||
) -> Result<Option<(PsdFile, Vec<String>)>, 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
|
||||
@@ -167,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;
|
||||
@@ -219,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);
|
||||
|
||||
@@ -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:?}"
|
||||
|
||||
@@ -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}")));
|
||||
|
||||
@@ -18,30 +18,36 @@ pub fn document_to_psd(doc: &Document) -> Result<PsdFile, crate::IoError> {
|
||||
|
||||
fn document_to_psd_with_pattern_limit(doc: &Document, limit: u64) -> Result<PsdFile, crate::IoError> {
|
||||
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<String>) {
|
||||
pub fn document_to_psd_with(doc: &Document, opts: &PsdExportOptions) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
pub(crate) fn document_to_psd_interruptible(doc: &Document, opts: &PsdExportOptions, ctl: &Interrupt) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
pub(super) fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, ctl: &Interrupt) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
pub(super) fn document_to_psd_sized(
|
||||
doc: &Document,
|
||||
opts: &PsdExportOptions,
|
||||
depth: u32,
|
||||
ctl: &Interrupt,
|
||||
size_limit: u64,
|
||||
) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
) -> Result<(PsdFile, Vec<String>), 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<String>) {
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String>) {
|
||||
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::<Vec<_>>()
|
||||
};
|
||||
@@ -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::<Vec<_>>();
|
||||
(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<usize>) -> (PsdFile, Vec<String>) {
|
||||
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");
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -679,7 +679,7 @@ fn photoshop_transparency_and_spot_tiff(doc: &Document, layers: bool) -> Vec<u8>
|
||||
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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in new issue
Block a user