From e879da042c8608c36b4dcf4b92a1dec438ba3aa0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 14:22:37 -0500 Subject: [PATCH] fix: preserve bounded annotation text and unchanged legacy bytes --- crates/io/src/annotation_shared_tests.rs | 31 ++++++++++++++++++++++++ crates/io/src/annotations_map.rs | 26 +++++++++++++++++--- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/io/src/annotation_shared_tests.rs b/crates/io/src/annotation_shared_tests.rs index dd77d18e06..d4f6ad69bf 100644 --- a/crates/io/src/annotation_shared_tests.rs +++ b/crates/io/src/annotation_shared_tests.rs @@ -90,3 +90,34 @@ fn text_cannot_cross_declared_record_boundary() { block[8..12].copy_from_slice(&(length - 2).to_be_bytes()); assert!(parse_entries(&block).is_none()); } + +#[test] +fn normalized_utf16_budget_counts_units_not_utf8_bytes() { + assert_eq!(text_bytes("✓✓✓", 8), Some(8)); + assert_eq!(text_bytes("𝄞", 6), Some(6)); + assert_eq!(text_bytes("a\r\nb\nc\r", 14), Some(14)); + assert_eq!(text_bytes("✓✓✓", 7), None); + assert_eq!(text_bytes("𝄞", 5), None); + let note = Note { text: "✓".repeat(3 * 1024 * 1024), ..Default::default() }; + assert!(write_anno(&[note], &[]).is_ok()); +} + +#[test] +fn unchanged_legacy_text_keeps_raw_bytes_without_utf16_rewrite() { + let mut block = legacy_anno(&[Note { text: "x".into(), ..Default::default() }], &[]); + let key = block.windows(4).position(|w| w == b"txtC").unwrap(); + block.truncate(key + 8); + block.extend(std::iter::repeat_n(b'x', 9 * 1024 * 1024)); + let size = u32::try_from(block.len() - key - 8).unwrap(); + block[key + 4..key + 8].copy_from_slice(&size.to_be_bytes()); + block[key - 4..key].copy_from_slice(&(size + 12).to_be_bytes()); + let record = u32::try_from(block.len() - 8).unwrap(); + block[8..12].copy_from_slice(&record.to_be_bytes()); + let mut doc = Document::new("notes", photocraft_doc::Size::new(1, 1), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + doc.notes = parse_anno(&block).unwrap(); + assert!(write_anno(&doc.notes, &[]).is_err()); + let blocks = vec![(*b"8BIM", ANNO, Arc::new(block))]; + assert_eq!(export_blocks(&doc, blocks.clone()).unwrap(), blocks); + doc.notes[0].text.push('x'); + assert!(export_blocks(&doc, blocks).is_err()); +} diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index acc802fa60..b56961723c 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -74,10 +74,25 @@ fn decode_text(data: &[u8]) -> String { s.trim_end_matches('\0').replace("\r\n", "\n").replace('\r', "\n") } +fn normalized_text(s: &str) -> impl Iterator + '_ { + let mut previous_cr = false; + s.chars().filter_map(move |c| { + let skip = previous_cr && c == '\n'; + previous_cr = c == '\r'; + if skip { None } else { Some(if c == '\n' { '\r' } else { c }) } + }) +} + +fn text_bytes(s: &str, limit: usize) -> Option { + normalized_text(s).try_fold(2usize, |bytes, c| bytes.checked_add(c.len_utf16() * 2).filter(|&n| n <= limit)) +} + fn encode_text(s: &str) -> Vec { let mut out = vec![0xFE, 0xFF]; - for u in s.replace("\r\n", "\n").replace('\n', "\r").encode_utf16() { - out.extend_from_slice(&u.to_be_bytes()); + for c in normalized_text(s) { + for u in c.encode_utf16(&mut [0; 2]) { + out.extend_from_slice(&u.to_be_bytes()); + } } out } @@ -117,7 +132,7 @@ pub fn parse_anno(data: &[u8]) -> Option> { fn write_note(n: &Note) -> craft_psd::Result> { let limits = craft_psd::annotations::Limits::default(); // Bound temporary text normalization before the shared fallible writer allocates. - if n.text.len().checked_mul(2).and_then(|n| n.checked_add(2)).is_none_or(|n| n > limits.bytes) { + if text_bytes(&n.text, limits.bytes).is_none() { return Err(craft_psd::PsdError::LimitExceeded("annotation text")); } let (x, y) = (n.position[0].round() as i32, n.position[1].round() as i32); @@ -188,6 +203,11 @@ pub fn export_blocks(doc: &Document, mut blocks: Vec> = entries.as_ref().map(|e| e.iter().filter_map(|e| if let Entry::Text(n) = e { Some(n.clone()) } else { None }).collect()); + // Unedited decoded notes retain the original bounded block, even when its legacy + // single-byte text would exceed the UTF-16 writer budget after conversion. + if parsed.as_deref() == Some(doc.notes.as_slice()) || (entries.is_none() && doc.notes.is_empty()) { + return Ok(blocks); + } // Compare in stored precision (colours are 16-bit, positions whole pixels, empty popups get a // default rectangle). let want = parse_anno(&write_anno(&doc.notes, &[]).map_err(|e| crate::IoError::Unsupported(e.to_string()))?);