Merge remote-tracking branch 'origin/main' into w15191

# Conflicts:
#	Cargo.lock
#	crates/io/Cargo.toml
This commit is contained in:
FredApps committed 2026-11-16 02:33:37 +01:00
commit 471d97c3c2
22 files changed
+387 -279

No files matched your search

Generated
+21 -9
View File
@@ -1352,7 +1352,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6#ad8faa1c136ce289e9f132c9137d0cd913bd4ef6"
source = "git+https://github.com/storytold/craft-libs?rev=c6eb84d427d81b6d64207654c8ee0516cd3d7324#c6eb84d427d81b6d64207654c8ee0516cd3d7324"
dependencies = [
"md-5",
"rayon",
@@ -1620,7 +1620,18 @@ 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",
@@ -5538,7 +5549,7 @@ dependencies = [
"craft-ai-agents",
"craft-flags",
"craft-image-codecs",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"getrandom 0.3.4",
"hmac",
"photocraft-color",
@@ -5572,7 +5583,7 @@ dependencies = [
"clap_mangen",
"craft-cms",
"craft-image-codecs",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"photocraft-automation",
"photocraft-doc",
"photocraft-engine",
@@ -5637,7 +5648,7 @@ dependencies = [
"craft-image-codecs",
"craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3e970577b9bb446967c2003ec8ecaf4f28b0768c)",
"craft-print",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"craft-xml",
"exr",
"flate2",
@@ -5740,7 +5751,8 @@ dependencies = [
"craft-ora",
"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=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=ad8faa1c136ce289e9f132c9137d0cd913bd4ef6)",
@@ -5873,7 +5885,7 @@ version = "0.23.1"
dependencies = [
"base64 0.23.1",
"craft-plist",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"flate2",
"parley",
"photocraft-color",
@@ -5895,7 +5907,7 @@ dependencies = [
"craft-i18n",
"craft-image-codecs",
"craft-print",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"craft-ui",
"craft-update",
"eframe",
@@ -5950,7 +5962,7 @@ name = "photocraft-web"
version = "0.23.1"
dependencies = [
"craft-image-codecs",
"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=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f)",
"eframe",
"egui",
"js-sys",
+2 -2
View File
@@ -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 = "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" }
@@ -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 = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c6eb84d427d81b6d64207654c8ee0516cd3d7324" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" }
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "ad8faa1c136ce289e9f132c9137d0cd913bd4ef6" }
+6 -22
View File
@@ -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",
]
);
}
}
+1
View File
@@ -30,6 +30,7 @@ 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 }
+130
View File
@@ -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(&note), &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
View File
@@ -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(&notes[..1], &[]);
let again = write_anno(&notes[..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;
+1 -11
View File
@@ -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;
+4 -41
View File
@@ -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.
+1 -1
View File
@@ -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() {
+6 -6
View File
@@ -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)]
+12 -10
View File
@@ -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);
+1 -1
View File
@@ -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:?}"
+2 -1
View File
@@ -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 -12
View File
@@ -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:?}");
}
}
+13 -12
View File
@@ -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");
+2 -2
View File
@@ -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());
+2 -2
View File
@@ -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();
+1 -1
View File
@@ -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]);
}
}
+1 -1
View File
@@ -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);
+5 -5
View File
@@ -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");
}