PhotoCraft: An open-source, photo editor written by scratch in pure Rust
test(io): an indexed GIF keeps its table and transparent entry; malformed GIFs give no table (#7886)
Korg1che92e5164a87e
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rsindex 3c28a8196..8e4f237f6 100644--- a/apps/photocraft-cli/tests/cli.rs+++ b/apps/photocraft-cli/tests/cli.rs@@ -163,19 +163,29 @@ fn info_and_convert_report_decode_warnings() {gif.extend_from_slice(b"\x2C\0\0\0\0\x01\0\x01\0\0\x02\x02\x44\x01\0");}gif.push(0x3B);+ // A GIF opens in Indexed Color (#7886), so `convert` to PNG also notes the palette PNG it+ // writes, after the decode warning.let cases = [- ("whole.jpg", &jpeg[..], None),- ("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing")),- ("anim.gif", &gif[..], Some("only the first of 3 frames was imported")),+ ("whole.jpg", &jpeg[..], None, None),+ ("half.jpg", &jpeg[..jpeg.len() / 2], Some("JPEG data ends early (the file is truncated or damaged); part of the image is missing"), None),+ ("anim.gif", &gif[..], Some("only the first of 3 frames was imported"), Some("written as an 8-bit palette PNG (2 colours)")),];- for (name, bytes, warning) in cases {+ for (name, bytes, warning, export) in cases {let file = d.join(name);std::fs::write(&file, bytes).unwrap();let (out, _) = ok(bin().arg("info").arg(&file).arg("--compact"));let v: Value = serde_json::from_str(&out).unwrap();assert_eq!(v["warnings"], json!(warning.into_iter().collect::<Vec<_>>()), "{name}");let (_, err) = ok(bin().arg("convert").arg(&file).arg(d.join(format!("{name}.png"))));- assert_eq!(err.trim(), warning.map(|w| format!("warning: {w}")).unwrap_or_default(), "{name}");+ let expected: Vec<String> = warning.into_iter().chain(export).map(|w| format!("warning: {w}")).collect();+ assert_eq!(+ err.trim(),+ expected.join(+ "+"+ ),+ "{name}"+ );}std::fs::remove_dir_all(d).unwrap();}diff --git a/crates/codecs/src/codecs/gif_palette.rs b/crates/codecs/src/codecs/gif_palette.rsindex aa71f0237..eb0a0e218 100644--- a/crates/codecs/src/codecs/gif_palette.rs+++ b/crates/codecs/src/codecs/gif_palette.rs@@ -62,3 +62,65 @@ pub(crate) fn palette(b: &[u8]) -> Option<(Vec<[u8; 3]>, Option<u8>)> {}}+#[cfg(test)]+mod tests {+ use super::palette;++ /// A GIF up to its first image: `global` table entries, optional GCE transparency, optional+ /// local table.+ fn gif(global: &[[u8; 3]], transparent: Option<u8>, local: Option<&[[u8; 3]]>) -> Vec<u8> {+ let size_bits = |n: usize| (n.max(2).next_power_of_two().trailing_zeros() - 1) as u8;+ let mut b = b"GIF89a".to_vec();+ b.extend([4, 0, 4, 0]);+ b.push(if global.is_empty() { 0 } else { 0x80 | size_bits(global.len()) });+ b.extend([0, 0]);+ let pad = |b: &mut Vec<u8>, t: &[[u8; 3]]| {+ let n = 2usize << size_bits(t.len());+ for k in 0..n {+ b.extend(t.get(k).copied().unwrap_or([0, 0, 0]));+ }+ };+ if !global.is_empty() {+ pad(&mut b, global);+ }+ // A comment extension first, to skip.+ b.extend([0x21, 0xFE, 3, b'h', b'i', b'!', 0]);+ if let Some(i) = transparent {+ b.extend([0x21, 0xF9, 4, 0x01, 0, 0, i, 0]);+ }+ b.extend([0x2C, 0, 0, 0, 0, 4, 0, 4, 0]);+ match local {+ Some(t) => {+ b.push(0x80 | size_bits(t.len()));+ pad(&mut b, t);+ }+ None => b.push(0),+ }+ b.extend([2, 2, 0x4C, 0x01, 0, 0x3B]);+ b+ }++ #[test]+ fn the_first_frames_table_and_transparent_entry() {+ let g = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]];+ assert_eq!(palette(&gif(&g, None, None)), Some((g.to_vec(), None)));+ assert_eq!(palette(&gif(&g, Some(2), None)), Some((g.to_vec(), Some(2))));+ // A local table wins over the global one.+ let l = [[1, 2, 3], [4, 5, 6]];+ assert_eq!(palette(&gif(&g, Some(1), Some(&l))), Some((l.to_vec(), Some(1))));+ // A transparent index past the table is no transparent entry.+ assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None)));+ }++ #[test]+ fn no_table_or_not_a_gif_is_none() {+ assert_eq!(palette(&gif(&[], None, None)), None, "no table at all");+ assert_eq!(palette(b"\x89PNG\r\n\x1a\n"), None);+ assert_eq!(palette(b""), None);+ let whole = gif(&[[9, 9, 9], [8, 8, 8]], Some(0), None);+ for cut in 0..whole.len() - 6 {+ // Cut short anywhere before the image descriptor's fields: never a panic.+ let _ = palette(&whole[..cut]);+ }+ }+}diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rsindex e591fbd5c..72126d0bc 100644--- a/crates/io/tests/flat.rs+++ b/crates/io/tests/flat.rs@@ -118,6 +118,60 @@ fn indexed_png_opens_with_its_color_table() {assert_eq!(s.rgba(0, 1)[3], 0.0, "the tRNS entry is transparent");}+/// A 2 × 2 GIF89a of palette indices `idx` over `pal` (padded to 4 entries), with `transparent`+/// set through a Graphic Control Extension. Its LZW stream clears before every pixel, so every+/// code stays 3 bits: the simplest valid stream any decoder reads.+fn indexed_gif(pal: &[[u8; 3]; 4], idx: [u8; 4], transparent: Option<u8>) -> Vec<u8> {+ let mut b = b"GIF89a".to_vec();+ b.extend([2, 0, 2, 0, 0x81, 0, 0]); // 2 × 2, global table of 4+ pal.iter().for_each(|c| b.extend(c));+ if let Some(t) = transparent {+ b.extend([0x21, 0xF9, 4, 0x01, 0, 0, t, 0]);+ }+ b.extend([0x2C, 0, 0, 0, 0, 2, 0, 2, 0, 0]);+ let (clear, end) = (4u32, 5u32);+ let codes: Vec<u32> = idx.iter().flat_map(|&i| [clear, u32::from(i)]).chain([end]).collect();+ let (mut bits, mut n, mut data) = (0u32, 0u32, Vec::new());+ for c in codes {+ bits |= c << n;+ n += 3;+ while n >= 8 {+ data.push((bits & 0xFF) as u8);+ bits >>= 8;+ n -= 8;+ }+ }+ if n > 0 {+ data.push(bits as u8);+ }+ b.push(2); // LZW minimum code size+ b.push(data.len() as u8);+ b.extend(&data);+ b.extend([0, 0x3B]);+ b+}++/// An indexed GIF opens in Indexed Color mode with its colour table and transparent entry, as a+/// palette PNG does (#7886); it used to open as RGB.+#[test]+fn indexed_gif_opens_with_its_color_table() {+ let pal = [[10, 20, 30], [200, 100, 50], [7, 8, 9], [0, 255, 0]];+ let doc = import("indexed.gif", &indexed_gif(&pal, [1, 0, 2, 1], Some(2))).unwrap().document;+ assert_eq!(doc.mode, ColorMode::Indexed);+ assert_eq!(doc.depth, SampleType::U8);+ let table = doc.color_table.as_ref().unwrap();+ assert_eq!(table.colors, pal, "every entry, used or not");+ assert_eq!(table.transparent, Some(2));+ let s = doc.layers[0].surface().unwrap();+ let px = s.rgba(0, 0);+ assert!((px[0] - 200.0 / 255.0).abs() < 1e-6 && (px[3] - 1.0).abs() < 1e-6, "{px:?}");+ assert_eq!(s.rgba(0, 1)[3], 0.0, "the transparent entry is transparent");+ // Without a transparent entry, the table alone.+ let doc = import("opaque.gif", &indexed_gif(&pal, [3, 3, 0, 1], None)).unwrap().document;+ assert_eq!(doc.mode, ColorMode::Indexed);+ assert_eq!(doc.color_table.as_ref().unwrap().transparent, None);+}+/// FITS header cards travel as the document's text metadata, so an astro frame keeps its/// OBJECT, EXPTIME and the rest through an edit.#[test]