PhotoCraft: An open-source, photo editor written by scratch in pure Rust
feat(codecs): add XPM2 plain-text image import support (#4264)
Nigel Ihza Firdausy4a53fad835bb
diff --git a/crates/codecs/src/codecs/xpm.rs b/crates/codecs/src/codecs/xpm.rsindex 36062f04d..82543d886 100644--- a/crates/codecs/src/codecs/xpm.rs+++ b/crates/codecs/src/codecs/xpm.rs@@ -1,5 +1,6 @@-//! XPM3 reader for C-source icon arrays. Supports transparency (None), RGB hex-//! at 4/8/16 bits per channel, and common X11 colour names. Does not run C code.+//! X PixMap reader for XPM2 plain-text icons and XPM3 C-source icon arrays.+//! Supports transparency (None), RGB hex at 4/8/16 bits per channel and+//! common X11 colour names. Does not execute C code.use std::collections::HashMap;@@ -68,6 +69,27 @@ fn c_strings(bytes: &[u8]) -> Result<Vec<Vec<u8>>, CodecError> {Ok(lines)}+/// Extract XPM2's plain-text lines without trimming pixel rows: leading and+/// trailing spaces can be palette keys, and physical CRLF is not image data.+fn xpm2_lines(bytes: &[u8]) -> Result<Vec<Vec<u8>>, CodecError> {+ let mut input = bytes.split(|&b| b == b'\n');+ let header = input.next().ok_or_else(|| bad("missing XPM2 marker"))?;+ if header.strip_suffix(b"\r").unwrap_or(header) != b"! XPM2" {+ return Err(bad("not an XPM2 image"));+ }+ let mut lines = Vec::new();+ for raw in input {+ let line = raw.strip_suffix(b"\r").unwrap_or(raw);+ // The header may be preceded by comments and blank lines. After the+ // header, a leading '!' is allowed as a palette key or pixel value.+ if lines.is_empty() && (line.is_empty() || line.starts_with(b"!")) {+ continue;+ }+ lines.push(line.to_vec());+ }+ Ok(lines)+}+fn channel(hex: &str) -> Option<u8> {let v = u32::from_str_radix(hex, 16).ok()?;let max = (1u32 << (hex.len() * 4)) - 1;@@ -117,13 +139,20 @@ fn color(name: &str) -> Option<[u8; 4]> {}pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {- if !bytes.starts_with(b"/* XPM */") {- return Err(bad("not an XPM3 image"));- }if bytes.len() > MAX_SOURCE {return Err(CodecError::LimitExceeded("XPM source exceeds 256 MiB".into()));}- let lines = c_strings(bytes)?;+ let lines = if bytes.starts_with(b"/* XPM */") {+ c_strings(bytes)?+ } else if bytes.starts_with(b"! XPM2\n") || bytes.starts_with(b"! XPM2\r\n") {+ xpm2_lines(bytes)?+ } else {+ return Err(bad("not an XPM2/XPM3 image"));+ };+ decode_lines(&lines, limits)+}++fn decode_lines(lines: &[Vec<u8>], limits: &Limits) -> Result<Image, CodecError> {let header = lines.first().ok_or_else(|| bad("missing image header"))?;let parts = std::str::from_utf8(header).map_err(|_| bad("non-UTF-8 XPM header"))?;let mut parts = parts.split_ascii_whitespace();diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rsindex ac5fb3948..e1e0927fa 100644--- a/crates/codecs/src/format.rs+++ b/crates/codecs/src/format.rs@@ -17,7 +17,7 @@ pub enum Format {Pnm,/// ZSoft Paintbrush: 1/2/4-bit planar palettes, 8-bit indexed and 24-bit RGB.Pcx,- /// X PixMap icons (XPM3 C-string representation).+ /// X PixMap icons (XPM2 plain text and XPM3 C-string arrays).Xpm,Qoi,OpenExr,@@ -296,7 +296,7 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {if b.starts_with(b"SIMPLE =") {return Some(Format::Fits);}- if b.starts_with(b"/* XPM */") {+ if b.starts_with(b"/* XPM */") || b.starts_with(b"! XPM2\n") || b.starts_with(b"! XPM2\r\n") {return Some(Format::Xpm);}if crate::codecs::pcx::looks_like_pcx(b) {diff --git a/crates/codecs/tests/xpm.rs b/crates/codecs/tests/xpm.rsindex 8727e5dbc..aa0b3bf0b 100644--- a/crates/codecs/tests/xpm.rs+++ b/crates/codecs/tests/xpm.rs@@ -84,6 +84,36 @@ static char *icon[] = {assert_eq!(image.data(), &[190, 190, 190, 255, 176, 48, 96, 255, 160, 32, 240, 255, 250, 250, 210, 255, 82, 139, 139, 255, 248, 248, 255, 255,]);}+#[test]+fn xpm2_decodes_crlf_comments_spaces_and_multichar_keys() {+ let bytes = b"! XPM2\r\n! exported by an icon tool\r\n2 2 3 2\r\n.a c #f00\r\n!_ c None\r\nzz c DarkBlue\r\n.a!_\r\nzz.a\r\n";+ assert_eq!(detect(bytes), Some(Format::Xpm));+ let image = decode(bytes).unwrap();+ assert_eq!(image.dimensions(), (2, 2));+ assert_eq!(image.data(), &[255, 0, 0, 255, 0, 0, 0, 0, 0, 0, 139, 255, 255, 0, 0, 255]);+}++#[test]+fn xpm2_allows_exclamation_as_a_pixel_key_and_preserves_space_keys() {+ let bytes = b"! XPM2\n2 1 2 1\n! c red\n c None\n! \n";+ let image = decode(bytes).unwrap();+ assert_eq!(image.data(), &[255, 0, 0, 255, 0, 0, 0, 0]);+}++#[test]+fn xpm2_malformed_inputs_return_errors() {+ for bytes in [+ &b"! XPM2\n1 1 1 1\na c black\n"[..],+ &b"! XPM2\n1 1 1 1\na c black\nb\n"[..],+ &b"! XPM2\n1 1 1 1\na c #a\xc3\xa9\na\n"[..],+ &b"! XPM2 invalid\n1 1 1 1\na c black\na\n"[..],+ &b"! XPM2\n100000 100000 1 1\na c red\na\n"[..],+ ] {+ assert!(decode_as(Format::Xpm, bytes).is_err(), "{bytes:?}");+ }+ assert_ne!(detect(b"! XPM23\n1 1 1 1\na c black\na\n"), Some(Format::Xpm));+}+#[test]fn xpm_is_import_only() {assert!(caps(Format::Xpm).read);