From de97c35f2b2af01c62371647e57a6affeab456fd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 22:30:28 -0500 Subject: [PATCH] craft-palette: share bounded GIMP palette reading from AniCraft (#1977) --- ATTRIBUTION.md | 4 ++ Cargo.lock | 4 ++ Cargo.toml | 1 + crates/palette/Cargo.toml | 11 +++++ crates/palette/src/lib.rs | 97 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 117 insertions(+) create mode 100644 crates/palette/Cargo.toml create mode 100644 crates/palette/src/lib.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 02935bac6..9d260300c 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -110,3 +110,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## Non-seeking WAV primitives `crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. + +## GIMP palette reader + +`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. diff --git a/Cargo.lock b/Cargo.lock index 74732b6d6..1ac11475f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2592,6 +2592,10 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-palette" +version = "0.1.0" + [[package]] name = "craft-pcraft-bundle" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 72ae0083a..2c0f4dfea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-palette = { path = "crates/palette" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/palette/Cargo.toml b/crates/palette/Cargo.toml new file mode 100644 index 000000000..d39a80b67 --- /dev/null +++ b/crates/palette/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-palette" +description = "Bounded, application-independent GIMP palette reading" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/palette/src/lib.rs b/crates/palette/src/lib.rs new file mode 100644 index 000000000..c49b0666d --- /dev/null +++ b/crates/palette/src/lib.rs @@ -0,0 +1,97 @@ +//! GIMP palette (.gpl) reading with neutral RGB8 colours and names. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Largest accepted palette, bounding all parsing allocations. +pub const MAX_BYTES: usize = 1 << 20; +/// Maximum colours returned; later rows are ignored. +pub const MAX_COLORS: usize = 1024; +/// A named RGB colour. Display-name sanitization belongs to the caller. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Color { + /// Whitespace-normalized colour label; "Untitled" remains literal. + pub name: String, + /// Red, green and blue channels. + pub rgb: [u8; 3], +} +/// A palette's title and colours, in file order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Palette { + /// Last Name header before the colour limit; leading value whitespace is retained. + pub name: String, + /// Valid colour rows in file order. + pub colors: Vec, +} +/// Reads GPL text, accepting BOM/CRLF, comments and metadata headers. +/// Malformed colour rows are skipped. Missing magic, empty palettes and oversized +/// input are errors. Columns and Channels headers are ignored for legacy compatibility. +pub fn parse_gpl(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err("the palette file is too large".into()); + } + let mut lines = text.lines(); + let first = lines.next().unwrap_or("").trim_start_matches('\u{feff}').trim(); + if first != "GIMP Palette" { + return Err("this isn't a GIMP palette (its first line must be \"GIMP Palette\")".into()); + } + let mut name = String::new(); + let mut out = Vec::new(); + for line in lines { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') { + continue; + } + if let Some(n) = l.strip_prefix("Name:") { + name = n.to_string(); + continue; + } + if l.starts_with("Columns:") || l.starts_with("Channels:") { + continue; + } + let mut parts = l.split_whitespace(); + let channel = |s: Option<&str>| s.and_then(|v| v.parse::().ok()).filter(|v| *v <= 255).map(|v| v as u8); + let (Some(r), Some(g), Some(b)) = (channel(parts.next()), channel(parts.next()), channel(parts.next())) else { continue }; + let rest: Vec<&str> = parts.collect(); + let label = rest.join(" "); + out.push(Color { name: label, rgb: [r, g, b] }); + if out.len() >= MAX_COLORS { + break; + } + } + if out.is_empty() { + return Err("the palette has no colours in it".into()); + } + Ok(Palette { name, colors: out }) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn metadata_rgb_names_and_legacy_rows() { + let p = parse_gpl("\u{feff}GIMP Palette\r\nName: First\r\nName: Last\nColumns: 4\nChannels: RGB\n# comment\n255 0 128 Pink ink\n256 0 0 invalid\n-1 2 3 invalid\n1 2 3 Untitled\n4 5 6\n").unwrap(); + assert_eq!(p.name, " Last"); + assert_eq!( + p.colors, + vec![ + Color { name: "Pink ink".into(), rgb: [255, 0, 128] }, + Color { name: "Untitled".into(), rgb: [1, 2, 3] }, + Color { name: String::new(), rgb: [4, 5, 6] } + ] + ); + } + + #[test] + fn limits_and_empty_input() { + for text in ["", "not a palette", "GIMP Palette", "GIMP Palette\n256 0 0"] { + assert!(parse_gpl(text).is_err()); + } + assert!(parse_gpl(&"x".repeat(MAX_BYTES + 1)).is_err()); + let many = format!("GIMP Palette\n{}Name: ignored", "1 2 3 é\n".repeat(MAX_COLORS + 1)); + let p = parse_gpl(&many).unwrap(); + assert_eq!(p.colors.len(), MAX_COLORS); + assert!(p.name.is_empty()); + assert_eq!(p.colors[0].name, "é"); + } +}