diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e40c1b4bc..c03a3a076 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -20,6 +20,9 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: pdf-test-fonts: true + # The instrumented build runs without a dependency cache: its 1.2 GB entry does not fit the + # repository's 10 GB cache budget beside the Workspace gate's. It runs on main only. + build-cache: false # The codec and format code behind features that are off by default. Without these the # coverage build never compiles it, and new code there reads as untested. cargo-features: >- diff --git a/Cargo.lock b/Cargo.lock index 7fc61e0bf..b93bdc572 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1902,6 +1902,7 @@ dependencies = [ "craft-smime", "craft-sniff", "craft-sourcemap", + "craft-sqlite", "craft-ssip", "craft-stencilcraft-document", "craft-stencilcraft-format", @@ -2319,11 +2320,13 @@ dependencies = [ name = "craft-develop" version = "0.1.0" dependencies = [ + "craft-color-transform", "craft-develop-model", "craft-render-parity", "proptest", "rayon", "serde", + "serde_json", ] [[package]] @@ -2644,6 +2647,7 @@ dependencies = [ "craft-dxf", "craft-eps", "craft-file-formats", + "craft-image-codecs", "craft-pdf 0.1.0", "craft-raster-codecs", "craft-svg", @@ -3954,6 +3958,10 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-sqlite" +version = "0.1.0" + [[package]] name = "craft-ssip" version = "0.1.0" @@ -4457,6 +4465,7 @@ dependencies = [ name = "craft-usd" version = "0.1.0" dependencies = [ + "half", "lz4_flex", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index 4c599679e..e8d31c840 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ craft-xfdf = { path = "crates/xfdf" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } +craft-sqlite = { path = "crates/sqlite" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/anicraft-format/src/lib.rs b/crates/anicraft-format/src/lib.rs index 7cc5dc261..6ff5d81e1 100644 --- a/crates/anicraft-format/src/lib.rs +++ b/crates/anicraft-format/src/lib.rs @@ -34,7 +34,12 @@ struct EnvelopeOut<'a, P, T> { /// Serializes the envelope in its stable wire order and uses AniCraft's compact/pretty threshold. pub fn write(generator: &str, paths: &[P], document: &T) -> Result { - let envelope = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator, paths, document }; + write_version(FORMAT_VERSION, generator, paths, document) +} + +/// Serializes the envelope with an explicit format version and AniCraft's compact/pretty threshold. +pub fn write_version(version: u32, generator: &str, paths: &[P], document: &T) -> Result { + let envelope = EnvelopeOut { format: FORMAT_NAME, version, generator, paths, document }; let compact = serde_json::to_string(&envelope)?; if compact.len() < PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) } } diff --git a/crates/color-transform/src/cct.rs b/crates/color-transform/src/cct.rs index 1f81cdb19..413ca5e6e 100644 --- a/crates/color-transform/src/cct.rs +++ b/crates/color-transform/src/cct.rs @@ -240,4 +240,24 @@ mod tests { assert_eq!(xy_to_temp_tint(p), (6500.0, 0.0), "{p:?}"); } } + + /// Pins the current behavior for warm, strongly green illuminants (e.g. 2000–3500 K with high + /// positive tint) where the source white's Bradford blue cone response is `<= 0.0`. The + /// checked Bradford path currently returns `Mat3::IDENTITY` there (so `wb_matrix` is + /// `REC2020.from_xyz() * REC2020.to_xyz()`, i.e. identity within `f64` rounding) rather than + /// inverting blue; final `#587` process-version policy for this region remains open. + #[test] + fn warm_green_wb_with_non_positive_cone_response_returns_identity() { + for (t, tint) in [(2000.0, 30.0), (2500.0, 60.0), (3000.0, 100.0), (3500.0, 125.0)] { + let src = temp_tint_to_xy(t, tint); + assert_eq!(crate::bradford(src, REC2020.white), Mat3::IDENTITY, "{t} K tint {tint}"); + let m = wb_matrix(&REC2020, src); + for (i, row) in m.0.iter().enumerate() { + for (j, &val) in row.iter().enumerate() { + let want = if i == j { 1.0 } else { 0.0 }; + assert!((val - want).abs() < 1e-12, "{t} K tint {tint} [{i}][{j}] = {val}"); + } + } + } + } } diff --git a/crates/color-transform/src/curve.rs b/crates/color-transform/src/curve.rs index cdf135cd5..5a7d482b2 100644 --- a/crates/color-transform/src/curve.rs +++ b/crates/color-transform/src/curve.rs @@ -225,6 +225,32 @@ impl Lut1 { } } + /// Resample this table to `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]). + pub fn resample(&self, n: usize) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + if self.v.len() == n { + return self.clone(); + } + Lut1::from_fn(n, |x| self.eval(x)) + } + + /// `self ∘ inner` sampled at `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]). + /// + /// Preserves fixed-size GPU LUT contracts (such as 1,024-entry shader tables) where + /// [`Lut1::compose`] would expand to the common refinement grid. When `inner` is empty it + /// resamples `self` to `n` entries; when `inner` already has `n` entries it evaluates `self` + /// directly at each of `inner`'s samples. + pub fn compose_len(&self, inner: &Lut1, n: usize) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + if inner.v.is_empty() { + return self.resample(n); + } + if inner.v.len() == n { + return Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() }; + } + Lut1::from_fn(n, |x| self.eval(inner.eval(x))) + } + pub fn is_identity(&self) -> bool { let n = self.v.len(); n >= 2 && self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) @@ -319,6 +345,21 @@ mod tests { assert_eq!(a.compose(&Lut1 { v: vec![] }), a); } + #[test] + fn compose_len_preserves_fixed_gpu_lut_size() { + const N: usize = 1024; + let a = Lut1::from_fn(N, |x| x * x); + let b = Lut1::from_fn(N, f32::sqrt); + let c = a.compose_len(&b, N); + assert_eq!(c.v.len(), N); + assert!((c.eval(0.3) - 0.3).abs() < 2e-3); + assert_eq!(a.compose_len(&Lut1 { v: vec![] }, N), a); + let small = Lut1::from_fn(17, f32::sqrt); + let d = a.compose_len(&small, N); + assert_eq!(d.v.len(), N); + assert!((d.eval(0.3) - a.eval(small.eval(0.3))).abs() < 2e-3); + } + /// A short `inner` does not drop the outer table's points between its own. #[test] fn composing_with_a_short_table_keeps_the_outer_curve() { diff --git a/crates/color-transform/src/lib.rs b/crates/color-transform/src/lib.rs index 7708cd75e..1c3791000 100644 --- a/crates/color-transform/src/lib.rs +++ b/crates/color-transform/src/lib.rs @@ -18,4 +18,6 @@ pub mod oklab; mod space; pub mod tonemap; -pub use space::{BRADFORD, D50, D65, DISPLAY_P3, Mat3, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz}; +pub use space::{ + ADOBE_RGB, BRADFORD, D50, D65, DISPLAY_P3, Mat3, PROPHOTO, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz, +}; diff --git a/crates/color-transform/src/space.rs b/crates/color-transform/src/space.rs index c0c1da382..d067d878a 100644 --- a/crates/color-transform/src/space.rs +++ b/crates/color-transform/src/space.rs @@ -118,6 +118,11 @@ pub const REC601_525: RgbSpace = RgbSpace { r: Xy::new(0.630, 0.340), g: Xy::new pub const REC2020: RgbSpace = RgbSpace { r: Xy::new(0.708, 0.292), g: Xy::new(0.170, 0.797), b: Xy::new(0.131, 0.046), white: D65 }; /// The DCI-P3 primaries with a D65 white (SMPTE EG 432-1). pub const DISPLAY_P3: RgbSpace = RgbSpace { r: Xy::new(0.680, 0.320), g: Xy::new(0.265, 0.690), b: Xy::new(0.150, 0.060), white: D65 }; +/// ProPhoto RGB (ROMM RGB, ISO 22028-2) primaries with a D50 white. +pub const PROPHOTO: RgbSpace = + RgbSpace { r: Xy::new(0.734699, 0.265301), g: Xy::new(0.159597, 0.840403), b: Xy::new(0.036598, 0.000105), white: D50 }; +/// The 1998 Adobe RGB primaries with a D65 white. +pub const ADOBE_RGB: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.21, 0.71), b: Xy::new(0.15, 0.06), white: D65 }; impl From for RgbSpace { fn from(p: Primaries) -> RgbSpace { @@ -292,4 +297,16 @@ mod tests { let m: [[f64; 3]; 3] = read.to_xyz().into(); assert_eq!(Mat3::from(m), read.to_xyz()); } + + #[test] + fn prophoto_and_adobe_rgb_map_white_and_roundtrip() { + for sp in [PROPHOTO, ADOBE_RGB] { + let w = sp.to_space(&REC2020).apply([1.0, 1.0, 1.0]); + assert!(w.iter().all(|c| (c - 1.0).abs() < 1e-3), "{sp:?} -> {w:?}"); + } + let a = SRGB.to_space(&PROPHOTO); + let b = PROPHOTO.to_space(&SRGB); + let v = b.apply(a.apply([0.2, 0.5, 0.9])); + assert!((v[0] - 0.2).abs() < 1e-9 && (v[1] - 0.5).abs() < 1e-9 && (v[2] - 0.9).abs() < 1e-9); + } } diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index be0f45c04..2731147cd 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -220,6 +220,7 @@ craft-gpu-providers = { workspace = true, optional = true } craft-gpu-wgpu = { workspace = true, optional = true } craft-ipp = { workspace = true, optional = true } craft-ppt-binary = { workspace = true, optional = true } +craft-sqlite = { workspace = true, optional = true } [features] ui = [ @@ -509,6 +510,7 @@ heif-testdata = ["heif", "craft-heif/testdata"] html = ["dep:craft-html"] html-flow = ["html", "craft-html/flow"] +html-standalone = ["html", "craft-html/standalone"] http-url = ["dep:craft-http-url"] @@ -596,6 +598,8 @@ media-source = ["dep:craft-media-source"] menu = ["dep:craft-menu"] mesh = ["dep:craft-mesh"] +mesh-abc = ["mesh", "craft-mesh/abc"] +mesh-dae = ["mesh", "craft-mesh/dae"] mesh-fbx = ["mesh", "craft-mesh/fbx"] mesh-gltf = ["mesh", "craft-mesh/gltf"] mesh-obj = ["mesh", "craft-mesh/obj"] @@ -643,6 +647,7 @@ pdf-content = ["pdf", "craft-pdf/content"] pdf-cos = ["pdf", "craft-pdf/cos"] pdf-crypt = ["pdf", "craft-pdf/crypt"] pdf-filters = ["pdf", "craft-pdf/filters"] +pdf-fonts = ["pdf", "craft-pdf/fonts"] pdf-interpret = ["pdf", "craft-pdf/interpret"] pdf-paths = ["pdf", "craft-pdf/paths"] pdf-raster = ["pdf", "craft-pdf/raster"] @@ -763,6 +768,8 @@ sniff = ["dep:craft-sniff"] sourcemap = ["dep:craft-sourcemap"] +sqlite = ["dep:craft-sqlite"] + ssip = ["dep:craft-ssip"] stencilcraft-document = ["dep:craft-stencilcraft-document"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 06a416a30..04ce86691 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -333,6 +333,8 @@ pub use craft_smime as smime; pub use craft_sniff as sniff; #[cfg(feature = "sourcemap")] pub use craft_sourcemap as sourcemap; +#[cfg(feature = "sqlite")] +pub use craft_sqlite as sqlite; #[cfg(feature = "ssip")] pub use craft_ssip as ssip; #[cfg(feature = "stencilcraft-document")] diff --git a/crates/dds/src/bptc.rs b/crates/dds/src/bptc.rs new file mode 100644 index 000000000..e6a5f317d --- /dev/null +++ b/crates/dds/src/bptc.rs @@ -0,0 +1,1152 @@ +//! BPTC blocks: BC7 (8-bit RGBA) and BC6H (half-float RGB), written from the Khronos Data Format +//! Specification's "BPTC Compressed Texture Image Formats" section. Each 16-byte block holds 4×4 +//! texels, row by row. Tables are the specification's, numbered as it numbers them. + +/// A block's bits, read from the lowest up. +struct Bits { + value: u128, + pos: u32, +} + +impl Bits { + fn new(block: &[u8; 16]) -> Self { + Self { value: u128::from_le_bytes(*block), pos: 0 } + } + + /// The next `n` bits (at most 16), as a number. + fn take(&mut self, n: u8) -> u32 { + let n = u32::from(n); + let mask = !u128::MAX.checked_shl(n).unwrap_or(0); + let out = self.value.checked_shr(self.pos).unwrap_or(0) & mask; + self.pos = self.pos.saturating_add(n); + out as u32 + } +} + +/// Interpolation weights by index bits (Table 119). +const WEIGHTS_2: [i32; 4] = [0, 21, 43, 64]; +const WEIGHTS_3: [i32; 8] = [0, 9, 18, 27, 37, 46, 55, 64]; +const WEIGHTS_4: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64]; + +fn weight(index_bits: u8, index: u32) -> i32 { + let table: &[i32] = match index_bits { + 2 => &WEIGHTS_2, + 3 => &WEIGHTS_3, + _ => &WEIGHTS_4, + }; + table.get(index as usize).copied().unwrap_or(0) +} + +/// Equation 2: a value between two endpoints. +fn interpolate(e0: i32, e1: i32, weight: i32) -> i32 { + ((64 - weight) * e0 + weight * e1 + 32) >> 6 +} + +/// Which subset texel `i` is in, for a block with `subsets` subsets and partition `partition`. +fn subset(subsets: u8, partition: usize, i: usize) -> usize { + let part = match subsets { + 2 => u32::from(PARTITIONS_2.get(partition).copied().unwrap_or(0)) >> i & 1, + 3 => PARTITIONS_3.get(partition).copied().unwrap_or(0) >> (2 * i) & 3, + _ => 0, + }; + part as usize +} + +/// Whether texel `i` is an anchor (its index is stored with one bit fewer). +fn anchor(subsets: u8, partition: usize, i: usize) -> bool { + let at = |table: &[u8; 64]| table.get(partition).is_some_and(|a| usize::from(*a) == i); + i == 0 + || match subsets { + 2 => at(&ANCHOR_2), + 3 => at(&ANCHOR_3_SECOND) || at(&ANCHOR_3_THIRD), + _ => false, + } +} + +/// The 16 indices of a block, each `bits` wide (anchors one fewer). +fn indices(r: &mut Bits, bits: u8, subsets: u8, partition: usize) -> [u32; 16] { + let mut out = [0; 16]; + for (i, x) in out.iter_mut().enumerate() { + *x = r.take(bits - u8::from(anchor(subsets, partition, i))); + } + out +} + +/// BC7's modes (Table 109): subsets, partition bits, rotation bits, index selection bits, colour +/// bits, alpha bits, per-endpoint P-bits, shared P-bits, index bits, secondary index bits. +const BC7_MODES: [[u8; 10]; 8] = [ + [3, 4, 0, 0, 4, 0, 1, 0, 3, 0], + [2, 6, 0, 0, 6, 0, 0, 1, 3, 0], + [3, 6, 0, 0, 5, 0, 0, 0, 2, 0], + [2, 6, 0, 0, 7, 0, 1, 0, 2, 0], + [1, 0, 2, 1, 5, 6, 0, 0, 2, 3], + [1, 0, 2, 0, 7, 8, 0, 0, 2, 2], + [1, 0, 0, 0, 7, 7, 1, 0, 4, 0], + [2, 6, 0, 0, 5, 5, 1, 0, 2, 0], +]; + +/// The 16 RGBA texels of a BC7 block. +pub fn bc7(block: &[u8; 16]) -> [[u8; 4]; 16] { + let mode = block[0].trailing_zeros(); + // A low byte of 0 is reserved: every channel of every texel is 0. + let Some(&[subsets, partition_bits, rotation_bits, selection_bits, colour_bits, alpha_bits, endpoint_p, shared_p, index_bits, index2_bits]) = + BC7_MODES.get(mode as usize) + else { + return [[0; 4]; 16]; + }; + let mut r = Bits::new(block); + r.pos = mode + 1; + let partition = r.take(partition_bits) as usize; + let rotation = r.take(rotation_bits); + let swapped = r.take(selection_bits) == 1; + let ends = usize::from(subsets) * 2; + // Endpoints: every endpoint's red, then green, blue and alpha; then the P-bits. + let mut raw = [[0u32; 4]; 6]; + for channel in 0..4 { + let bits = if channel < 3 { colour_bits } else { alpha_bits }; + for e in raw.iter_mut().take(ends) { + e[channel] = r.take(bits); + } + } + let mut p = [0u32; 6]; + if endpoint_p == 1 { + for x in p.iter_mut().take(ends) { + *x = r.take(1); + } + } + if shared_p == 1 { + for pair in p.chunks_mut(2).take(usize::from(subsets)) { + pair.fill(r.take(1)); + } + } + let has_p = endpoint_p + shared_p > 0; + let endpoints: [[i32; 4]; 6] = std::array::from_fn(|e| { + std::array::from_fn(|channel| { + let bits = u32::from(if channel < 3 { colour_bits } else { alpha_bits }); + let (v, bits) = match (raw[e][channel], bits) { + (_, 0) => return 255, + (v, bits) if has_p => (v << 1 | p[e], bits + 1), + other => other, + }; + // The stored bits are a byte's top bits; its top bits repeat into the rest. + (v << (8 - bits) | v >> (2 * bits - 8)) as i32 + }) + }); + let primary = indices(&mut r, index_bits, subsets, partition); + let secondary = if index2_bits > 0 { indices(&mut r, index2_bits, 1, 0) } else { [0; 16] }; + let (colour, colour_index_bits) = if swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + let (alpha, alpha_index_bits) = if index2_bits > 0 && !swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + std::array::from_fn(|i| { + let s = subset(subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let (wc, wa) = (weight(colour_index_bits, colour[i]), weight(alpha_index_bits, alpha[i])); + let mut px: [u8; 4] = std::array::from_fn(|c| interpolate(e0[c], e1[c], if c < 3 { wc } else { wa }) as u8); + if (1..=3).contains(&rotation) { + px.swap(rotation as usize - 1, 3); + } + px + }) +} + +// BC6H's fields: endpoint `e`'s red, green and blue are fields `3e`, `3e + 1` and `3e + 2`. +const R0: u8 = 0; +const G0: u8 = 1; +const B0: u8 = 2; +const R1: u8 = 3; +const G1: u8 = 4; +const B1: u8 = 5; +const R2: u8 = 6; +const G2: u8 = 7; +const B2: u8 = 8; +const R3: u8 = 9; +const G3: u8 = 10; +const B3: u8 = 11; +/// The partition number. +const PB: u8 = 12; + +/// A BC6H mode (Tables 121 and 122). +struct Bc6hMode { + id: u8, + /// Endpoints after the first are stored as differences from it. + transformed: bool, + subsets: u8, + endpoint_bits: u8, + /// Red, green and blue bits of the endpoints after the first. + delta_bits: [u8; 3], + /// After the mode bits, in block order: `(field, a, b)` is the spec's `field a..b`, so the + /// next `|a - b| + 1` bits of the block go to the field's bits `b`, `b ± 1`, …, `a`. + fields: &'static [(u8, u8, u8)], +} + +fn sign_extend(v: i32, bits: u8) -> i32 { + let shift = 32 - u32::from(bits); + (v << shift) >> shift +} + +/// An endpoint value stretched to 16 bits (the unquantization pseudocode). +fn unquantize(x: i32, bits: u8, signed: bool) -> i32 { + let n = i32::from(bits); + if !signed { + return match x { + _ if n >= 15 => x, + 0 => 0, + _ if x == (1 << n) - 1 => 0xffff, + _ => ((x << 15) + 0x4000) >> (n - 1), + }; + } + if n >= 16 { + return x; + } + let magnitude = match x.abs() { + 0 => 0, + a if a >= (1 << (n - 1)) - 1 => 0x7fff, + a => ((a << 15) + 0x4000) >> (n - 1), + }; + if x < 0 { -magnitude } else { magnitude } +} + +/// An interpolated value as a half float's bits. +fn finish(i: i32, signed: bool) -> u16 { + match (signed, i < 0) { + (false, _) => ((i * 31) >> 6) as u16, + (true, true) => (((-i * 31) >> 5) | 0x8000) as u16, + (true, false) => ((i * 31) >> 5) as u16, + } +} + +/// The 16 RGB texels of a BC6H block as half floats' bits; a reserved mode gives black. +fn bc6h_halves(block: &[u8; 16], signed: bool) -> [[u16; 3]; 16] { + let mut r = Bits::new(block); + let id = match r.take(2) { + low @ 0..=1 => low, + low => low | r.take(3) << 2, + }; + let Some(mode) = BC6H_MODES.iter().find(|m| u32::from(m.id) == id) else { + return [[0; 3]; 16]; + }; + let mut fields = [0i32; 13]; + for &(field, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + if let Some(f) = fields.get_mut(usize::from(field)) { + *f |= (r.take(1) as i32) << bit; + } + } + } + let bits = mode.endpoint_bits; + let ends = usize::from(mode.subsets) * 2; + let mut endpoints = [[0i32; 3]; 4]; + for (e, endpoint) in endpoints.iter_mut().enumerate().take(ends) { + for (c, v) in endpoint.iter_mut().enumerate() { + let (base, stored) = (fields[c], fields[3 * e + c]); + let x = match e { + 0 => stored, + _ if mode.transformed => (base + sign_extend(stored, mode.delta_bits[c])) & ((1 << bits) - 1), + _ => stored, + }; + *v = unquantize(if signed { sign_extend(x, bits) } else { x }, bits, signed); + } + } + let partition = fields[usize::from(PB)] as usize; + let index_bits = if mode.subsets == 2 { 3 } else { 4 }; + let index = indices(&mut r, index_bits, mode.subsets, partition); + std::array::from_fn(|i| { + let s = subset(mode.subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let w = weight(index_bits, index[i]); + std::array::from_fn(|c| finish(interpolate(e0[c], e1[c], w), signed)) + }) +} + +/// A half float's value. +pub fn half(h: u16) -> f32 { + let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 }; + let (exponent, mantissa) = (i32::from(h >> 10 & 31), f32::from(h & 1023)); + sign * match exponent { + 0 => mantissa * 2f32.powi(-24), + 31 if mantissa != 0.0 => f32::NAN, + 31 => f32::INFINITY, + e => (1024.0 + mantissa) * 2f32.powi(e - 25), + } +} + +/// A linear light value as an 8-bit sRGB value; 0..1 is kept, brighter and negative values clip. +pub fn srgb8(v: f32) -> u8 { + let v = v.clamp(0.0, 1.0); + let s = if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (s * 255.0 + 0.5) as u8 +} + +/// The 16 texels of a BC6H block, tone-mapped to 8-bit sRGB (opaque). +pub fn bc6h(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bc6h_halves(block, signed).map(|[r, g, b]| [srgb8(half(r)), srgb8(half(g)), srgb8(half(b)), 255]) +} + +/// Two-subset partitions (Table 114): bit `i` is texel `i`'s subset. +const PARTITIONS_2: [u16; 64] = [ + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, 0xf710, 0x008e, + 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, + 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, + 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +]; + +/// Three-subset partitions (Table 115): bits `2i` and `2i + 1` are texel `i`'s subset. +const PARTITIONS_3: [u32; 64] = [ + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, + 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, + 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, + 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, + 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +]; + +/// The anchor texel of the second subset of two-subset partitions (Table 118). +const ANCHOR_2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, + 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; + +/// The anchor texels of the second and third subsets of three-subset partitions (Tables 116, 117). +const ANCHOR_3_SECOND: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, + 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +]; + +const ANCHOR_3_THIRD: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, + 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// BC6H's modes, in the order of Table 121. +const BC6H_MODES: [Bc6hMode; 14] = [ + Bc6hMode { + id: 0, + transformed: true, + subsets: 2, + endpoint_bits: 10, + delta_bits: [5, 5, 5], + fields: &[ + (G2, 4, 4), + (B2, 4, 4), + (B3, 4, 4), + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 1, + transformed: true, + subsets: 2, + endpoint_bits: 7, + delta_bits: [6, 6, 6], + fields: &[ + (G2, 5, 5), + (G3, 4, 4), + (G3, 5, 5), + (R0, 6, 0), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 6, 0), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 6, 0), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 2, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [5, 4, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (R0, 10, 10), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 6, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 5, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (G0, 10, 10), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 3, 0), + (B3, 0, 0), + (B3, 2, 2), + (R3, 3, 0), + (G2, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 10, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 4, 5], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (B2, 4, 4), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B0, 10, 10), + (B2, 3, 0), + (R2, 3, 0), + (B3, 1, 1), + (B3, 2, 2), + (R3, 3, 0), + (B3, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 14, + transformed: true, + subsets: 2, + endpoint_bits: 9, + delta_bits: [5, 5, 5], + fields: &[ + (R0, 8, 0), + (B2, 4, 4), + (G0, 8, 0), + (G2, 4, 4), + (B0, 8, 0), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 18, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [6, 5, 5], + fields: &[ + (R0, 7, 0), + (G3, 4, 4), + (B2, 4, 4), + (G0, 7, 0), + (B3, 2, 2), + (G2, 4, 4), + (B0, 7, 0), + (B3, 3, 3), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 22, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 6, 5], + fields: &[ + (R0, 7, 0), + (B3, 0, 0), + (B2, 4, 4), + (G0, 7, 0), + (G2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (G3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 26, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 5, 6], + fields: &[ + (R0, 7, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 7, 0), + (B2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (B3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 30, + transformed: false, + subsets: 2, + endpoint_bits: 6, + delta_bits: [6, 6, 6], + fields: &[ + (R0, 5, 0), + (G3, 4, 4), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 5, 0), + (G2, 5, 5), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 5, 0), + (G3, 5, 5), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 3, + transformed: false, + subsets: 1, + endpoint_bits: 10, + delta_bits: [10, 10, 10], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 9, 0), (G1, 9, 0), (B1, 9, 0)], + }, + Bc6hMode { + id: 7, + transformed: true, + subsets: 1, + endpoint_bits: 11, + delta_bits: [9, 9, 9], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 8, 0), (R0, 10, 10), (G1, 8, 0), (G0, 10, 10), (B1, 8, 0), (B0, 10, 10)], + }, + Bc6hMode { + id: 11, + transformed: true, + subsets: 1, + endpoint_bits: 12, + delta_bits: [8, 8, 8], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 7, 0), (R0, 10, 11), (G1, 7, 0), (G0, 10, 11), (B1, 7, 0), (B0, 10, 11)], + }, + Bc6hMode { + id: 15, + transformed: true, + subsets: 1, + endpoint_bits: 16, + delta_bits: [4, 4, 4], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 3, 0), (R0, 10, 15), (G1, 3, 0), (G0, 10, 15), (B1, 3, 0), (B0, 10, 15)], + }, +]; + +#[cfg(test)] +mod tests { + use super::{B0, B1, B2, B3, BC6H_MODES, G0, G1, G2, G3, PB, R0, R1, R2, R3, bc6h, bc6h_halves, bc7, half, srgb8}; + + /// Pack `(value, bits)` fields into a block from the lowest bit up. + fn pack(fields: &[(u32, u32)]) -> [u8; 16] { + let (mut v, mut pos) = (0u128, 0); + for &(x, n) in fields { + assert!(u128::from(x) < 1 << n, "{x} doesn't fit in {n} bits"); + v |= u128::from(x) << pos; + pos += n; + } + assert_eq!(pos, 128, "a block is 128 bits"); + v.to_le_bytes() + } + + /// The mode bits of BC7 mode `m`, then `fields`. + fn bc7_block(m: u32, fields: &[(u32, u32)]) -> [u8; 16] { + pack(&[&[(1 << m, m + 1)], fields].concat()) + } + + /// One `bits`-wide field per value. + fn each(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + values.iter().map(|v| (*v, bits)).collect() + } + + /// 16 indices, `bits` wide, one bit fewer at the `anchors`. + fn texel_indices(values: [u32; 16], bits: u32, anchors: &[usize]) -> Vec<(u32, u32)> { + values.iter().enumerate().map(|(i, v)| (*v, bits - u32::from(anchors.contains(&i)))).collect() + } + + fn index_set(set: &[(usize, u32)]) -> [u32; 16] { + let mut out = [0; 16]; + for (i, v) in set { + out[*i] = *v; + } + out + } + + /// Grey endpoints: the same value in red, green and blue. + fn grey(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + [each(values, bits), each(values, bits), each(values, bits)].concat() + } + + // Each case's colours are worked out from the specification by hand: endpoint bits (and the + // P-bit) are a byte's top bits with its top bits repeated below, and a texel is + // ((64 - w) × e0 + w × e1 + 32) >> 6 with the weight w of its index. + + #[test] + fn bc7_mode_0_three_subsets_with_endpoint_p_bits() { + // Partition 0 of three subsets: rows 0011 / 0011 / 0221 / 2222; anchors 0, 3 and 15. + // Endpoints (4 bits + P-bit): 15+1 → 255, 0 → 0, 8+0 → 132, 8+1 → 140, 2+1 → 41, 4+0 → 66. + let idx = index_set(&[(1, 7), (2, 4), (3, 3), (9, 5), (15, 3)]); + let b = bc7_block( + 0, + &[&[(0, 4)], &grey(&[15, 0, 8, 8, 2, 4], 4)[..], &each(&[1, 0, 0, 1, 1, 0], 1), &texel_indices(idx, 3, &[0, 3, 15])].concat(), + ); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(255)); + assert_eq!(px[1], g(0), "index 7: the second endpoint"); + assert_eq!(px[2], g(137), "subset 1, weight 37: (27×132 + 37×140 + 32) >> 6"); + assert_eq!(px[3], g(135), "subset 1's anchor, weight 27"); + assert_eq!(px[9], g(59), "subset 2, weight 46: (18×41 + 46×66 + 32) >> 6"); + assert_eq!(px[15], g(52), "subset 2's anchor, weight 27"); + assert_eq!((px[8], px[10], px[11]), (g(255), g(41), g(132))); + } + + #[test] + fn bc7_mode_1_shared_p_bits() { + // Partition 13: texels 0-7 subset 0, 8-15 subset 1 (anchor 15). Endpoints (6 bits + + // shared P-bit): 63+1 → 255, 0+1 → 2; 32+0 → 129, 16+0 → 64. + let idx = index_set(&[(1, 7), (8, 2), (15, 3)]); + let b = bc7_block(1, &[&[(13, 6)], &grey(&[63, 0, 32, 16], 6)[..], &each(&[1, 0], 1), &texel_indices(idx, 3, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!((px[0], px[1], px[2]), (g(255), g(2), g(255))); + assert_eq!(px[8], g(111), "weight 18: (46×129 + 18×64 + 32) >> 6"); + assert_eq!(px[15], g(102), "anchor, weight 27"); + assert_eq!(px[9], g(129)); + } + + #[test] + fn bc7_mode_2_matches_the_specifications_example() { + // Partition 6 of three subsets: rows 0022 / 0022 / 1111 / 1111; anchors 0, 15 and 3 (the + // specification's worked example: texel 9 is subset 1, its index at bits 115-116). + // Endpoints (5 bits): 31 → 255, 0, 10 → 82, 20 → 165, 1 → 8, 30 → 247. + let idx = index_set(&[(0, 1), (2, 2), (3, 1), (9, 3), (15, 1)]); + let b = bc7_block(2, &[&[(6, 6)], &grey(&[31, 0, 10, 20, 1, 30], 5)[..], &texel_indices(idx, 2, &[0, 15, 3])].concat()); + assert_eq!(u128::from_le_bytes(b) >> 115 & 3, 3, "texel 9's index where the specification says"); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(171), "weight 21: (43×255 + 32) >> 6"); + assert_eq!(px[2], g(169), "subset 2, weight 43: (21×8 + 43×247 + 32) >> 6"); + assert_eq!(px[3], g(86), "subset 2's anchor, weight 21"); + assert_eq!(px[9], g(165)); + assert_eq!(px[15], g(109), "subset 1's anchor, weight 21: (43×82 + 21×165 + 32) >> 6"); + assert_eq!((px[1], px[8], px[6]), (g(255), g(82), g(8))); + } + + #[test] + fn bc7_mode_3_seven_bit_endpoints() { + // Partition 0: columns 2-3 are subset 1 (anchor 15). Endpoints (7 bits + P-bit): + // 100+1 → 201, 10+0 → 20, 127+1 → 255, 0+0 → 0. + let idx = index_set(&[(0, 1), (1, 2), (2, 3), (15, 1)]); + let b = bc7_block(3, &[&[(0, 6)], &grey(&[100, 10, 127, 0], 7)[..], &each(&[1, 0, 1, 0], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(142), "weight 21: (43×201 + 21×20 + 32) >> 6"); + assert_eq!(px[1], g(79), "weight 43"); + assert_eq!(px[2], g(0)); + assert_eq!(px[15], g(171)); + assert_eq!((px[3], px[4]), (g(255), g(201))); + } + + #[test] + fn bc7_mode_4_rotation_and_index_selection() { + // Rotation 1 swaps alpha and red; the selection bit takes colour from the 3-bit indices + // and alpha from the 2-bit ones. Red 31 → 255 to 0, green 0 to 255, blue 16 → 132, + // alpha (6 bits) 63 → 255 to 0. + let colour = index_set(&[(0, 3), (1, 7)]); + let alpha = index_set(&[(0, 1)]); + let ends = [each(&[31, 0, 0, 31, 16, 16], 5), each(&[63, 0], 6)].concat(); + let b = bc7_block(4, &[&[(1, 2), (1, 1)], &ends[..], &texel_indices(alpha, 2, &[0]), &texel_indices(colour, 3, &[0])].concat()); + let px = bc7(&b); + // Before the swap: red (37×255 + 32) >> 6 = 147, green 108, blue 132, alpha 171. + assert_eq!(px[0], [171, 108, 132, 147]); + assert_eq!(px[1], [255, 255, 132, 0]); + assert_eq!(px[2], [255, 0, 132, 255]); + } + + #[test] + fn bc7_mode_5_separate_alpha_indices() { + // Red 127 → 255 to 0, green 64 → 129, blue 0 to 255; alpha (8 bits) 200 to 100. + let colour = index_set(&[(0, 1), (5, 2)]); + let alpha = index_set(&[(0, 1), (5, 3)]); + let ends = [each(&[127, 0, 64, 64, 0, 127], 7), each(&[200, 100], 8)].concat(); + let b = bc7_block(5, &[&[(0, 2)], &ends[..], &texel_indices(colour, 2, &[0]), &texel_indices(alpha, 2, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171, 129, 84, 167], "weight 21 for colour and alpha: (43×200 + 21×100 + 32) >> 6"); + assert_eq!(px[5], [84, 129, 171, 100]); + assert_eq!(px[1], [255, 129, 0, 200]); + } + + #[test] + fn bc7_mode_6_four_bit_indices() { + // Endpoints (7 bits + P-bit) in every channel: [255, 1, 129, 255] and [0, 254, 64, 100]. + let idx = index_set(&[(0, 7), (1, 15), (2, 8)]); + let ends = each(&[127, 0, 0, 127, 64, 32, 127, 50], 7); + let b = bc7_block(6, &[&ends[..], &each(&[1, 0], 1), &texel_indices(idx, 4, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [135, 120, 99, 182], "the anchor's largest index, 7: weight 30"); + assert_eq!(px[1], [0, 254, 64, 100]); + assert_eq!(px[2], [120, 135, 94, 173], "weight 34: red (30×255 + 32) >> 6"); + assert_eq!(px[3], [255, 1, 129, 255]); + } + + #[test] + fn bc7_mode_7_two_subsets_with_alpha() { + // Partition 1: column 3 is subset 1 (anchor 15). Endpoints (5 bits + P-bit): + // [255; 4], [0; 4], [130, 0, 0, 251], [4, 134, 69, 4]. + let idx = index_set(&[(0, 1), (3, 3), (15, 1)]); + let ends = [each(&[31, 0, 16, 0], 5), each(&[31, 0, 0, 16], 5), each(&[31, 0, 0, 8], 5), each(&[31, 0, 31, 0], 5)].concat(); + let b = bc7_block(7, &[&[(1, 6)], &ends[..], &each(&[1, 0, 0, 1], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171; 4]); + assert_eq!(px[3], [4, 134, 69, 4]); + assert_eq!(px[15], [89, 44, 23, 170], "weight 21: red (43×130 + 21×4 + 32) >> 6"); + assert_eq!((px[7], px[1]), ([130, 0, 0, 251], [255; 4])); + } + + #[test] + fn bc7_reserved_block_is_all_zero() { + assert_eq!(bc7(&[0; 16]), [[0; 4]; 16]); + } + + /// A BC6H block of mode `id`: `values` by field (missing ones are 0), then the indices. + fn bc6h_block(id: u8, values: &[(u8, i32)], index: [u32; 16]) -> [u8; 16] { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let value = |f: u8| values.iter().find(|(g, _)| *g == f).map_or(0, |(_, v)| *v); + let mut fields = vec![(u32::from(id), if id < 2 { 2 } else { 5 })]; + for &(f, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + fields.push(((value(f) >> bit) as u32 & 1, 1)); + } + } + let bits = if mode.subsets == 2 { 3 } else { 4 }; + let partition = value(PB) as usize; + for (i, x) in index.iter().enumerate() { + fields.push((*x, bits - u32::from(super::anchor(mode.subsets, partition, i)))); + } + pack(&fields) + } + + /// The same endpoints for every mode: the first is (largest, 0, middle); the others are small + /// differences from it (or, without transformed endpoints, values near it). Two-subset modes + /// use partition 13 (texels 8-15 are subset 1); indices pick each endpoint and two blends. + fn bc6h_case(id: u8) -> ([u8; 16], Vec) { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let (max, mid, d) = ((1 << mode.endpoint_bits) - 1, 1 << (mode.endpoint_bits - 1), mode.delta_bits); + let mut v = vec![(R0, max), (G0, 0), (B0, mid)]; + if mode.transformed { + v.extend([(R1, -1), (G1, 1), (B1, 0)]); + } else { + v.extend([(R1, max - 1), (G1, 1), (B1, mid)]); + } + match (mode.transformed, mode.subsets) { + (true, 2) => v.extend([(R2, 0), (G2, 2), (B2, -2), (R3, -(1 << (d[0] - 1))), (G3, 0), (B3, 1), (PB, 13)]), + (false, 2) => v.extend([(R2, max), (G2, 2), (B2, mid - 2), (R3, 0), (G3, max), (B3, mid + 1), (PB, 13)]), + _ => {} + } + if mode.subsets == 2 { + (bc6h_block(id, &v, index_set(&[(1, 7), (8, 7), (2, 4), (9, 3)])), vec![0, 1, 2, 8, 9, 15]) + } else { + (bc6h_block(id, &v, index_set(&[(1, 15), (2, 8)])), vec![0, 1, 2]) + } + } + + // Half-float results for `bc6h_case`, from a separate decoder written from the specification's + // pseudocode. By hand, for mode 3's first texel: red is the largest 10-bit value → 0xffff → + // (0xffff × 31) >> 6 = 0x7bff (65504); blue 512 → ((512 << 15) + 0x4000) >> 9 = 32800 → + // (32800 × 31) >> 6 = 0x3e0f. Signed, red is -1 → -96 → 0x805d and blue -512 → -0x7fff → 0xfbff. + + const UNSIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x7bff, 0x0000, 0x3e0f], + [0x7bd1, 0x002e, 0x3e0f], + [0x7be4, 0x001b, 0x3e0f], + [0x7a00, 0x0000, 0x3e2e], + [0x7b27, 0x002d, 0x3df8], + [0x7bff, 0x004d, 0x3dd1], + ], + ), + ( + 1, + &[ + [0x7bff, 0x0000, 0x3e7c], + [0x7a8c, 0x0174, 0x3e7c], + [0x7b28, 0x00d7, 0x3e7c], + [0x5c84, 0x0000, 0x3f74], + [0x6eb7, 0x0166, 0x3dc5], + [0x7bff, 0x026c, 0x3c8c], + ], + ), + ( + 2, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b00, 0x0000, 0x3e17], + [0x7b93, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 6, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 10, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 14, + &[ + [0x7bff, 0x0000, 0x3e1f], + [0x7ba3, 0x005d, 0x3e1f], + [0x7bca, 0x0035, 0x3e1f], + [0x7801, 0x0000, 0x3e5d], + [0x7a4f, 0x0059, 0x3df1], + [0x7bff, 0x009b, 0x3da3], + ], + ), + ( + 18, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x6c42, 0x0000, 0x3eba], + [0x755b, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 22, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 26, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 30, + &[ + [0x7bff, 0x0000, 0x3ef8], + [0x7918, 0x02e8, 0x3ef8], + [0x7a51, 0x01ae, 0x3ef8], + [0x0000, 0x7bff, 0x40e8], + [0x47af, 0x371c, 0x3d8b], + [0x7bff, 0x04d8, 0x3b18], + ], + ), + (3, &[[0x7bff, 0x0000, 0x3e0f], [0x7bd1, 0x002e, 0x3e0f], [0x7be7, 0x0018, 0x3e0f]]), + (7, &[[0x7bff, 0x0000, 0x3e07], [0x7be8, 0x0017, 0x3e07], [0x7bf3, 0x000c, 0x3e07]]), + (11, &[[0x7bff, 0x0000, 0x3e03], [0x7bf4, 0x000b, 0x3e03], [0x7bf9, 0x0006, 0x3e03]]), + (15, &[[0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00]]), + ]; + const SIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x805d, 0x0000, 0xfbff], + [0x809b, 0x005d, 0xfbff], + [0x8080, 0x0036, 0xfbff], + [0x843d, 0x0000, 0xfbff], + [0x81ff, 0x005a, 0x132a], + [0x805d, 0x009b, 0x7ba3], + ], + ), + ( + 1, + &[ + [0x82e8, 0x0000, 0xfbff], + [0x84d8, 0x02e8, 0xfbff], + [0x8406, 0x01ae, 0xfbff], + [0xc0e8, 0x0000, 0xfbff], + [0x9d10, 0x02cc, 0x11b1], + [0x82e8, 0x04d8, 0x7918], + ], + ), + ( + 2, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x821e, 0x0000, 0xfbff], + [0x80ff, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 6, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 10, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 14, + &[ + [0x80ba, 0x0000, 0xfbff], + [0x8136, 0x00ba, 0xfbff], + [0x8101, 0x006b, 0xfbff], + [0x887a, 0x0000, 0xfbff], + [0x83ff, 0x00b3, 0x12f4], + [0x80ba, 0x0136, 0x7b46], + ], + ), + ( + 18, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0xa074, 0x0000, 0xfbff], + [0x8e88, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 22, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 26, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 30, + &[ + [0x85d0, 0x0000, 0xfbff], + [0x89b0, 0x05d0, 0xfbff], + [0x880d, 0x035c, 0xfbff], + [0x0000, 0x85d0, 0xfbff], + [0x835c, 0x0326, 0x1003], + [0x85d0, 0x09b0, 0x7630], + ], + ), + (3, &[[0x805d, 0x0000, 0xfbff], [0x809b, 0x005d, 0xfbff], [0x807d, 0x0031, 0xfbff]]), + (7, &[[0x802e, 0x0000, 0xfbff], [0x804d, 0x002e, 0xfbff], [0x803e, 0x0019, 0xfbff]]), + (11, &[[0x8017, 0x0000, 0xfbff], [0x8026, 0x0017, 0xfbff], [0x801f, 0x000c, 0xfbff]]), + (15, &[[0x8000, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00]]), + ]; + + #[test] + fn bc6h_every_mode_unsigned_and_signed() { + for (signed, expected) in [(false, &UNSIGNED), (true, &SIGNED)] { + for (id, want) in expected { + let (block, texels) = bc6h_case(*id); + let got = bc6h_halves(&block, signed); + let got: Vec<[u16; 3]> = texels.iter().map(|t| got[*t]).collect(); + assert_eq!(&got[..], *want, "mode {id}, signed {signed}"); + } + } + // Reserved modes (19, 23, 27, 31) are black. + for id in [19u32, 23, 27, 31] { + assert_eq!(bc6h_halves(&pack(&[(id, 5), (0, 123)]), false), [[0; 3]; 16]); + } + } + + #[test] + fn bc6h_tone_maps_to_srgb() { + assert_eq!([0x0000, 0x3800, 0x3c00, 0x7bff, 0xfc00, 0xbc00, 0x0001].map(|h| srgb8(half(h))), [0, 188, 255, 255, 0, 0, 0]); + assert_eq!(half(0x3555), 0.333_251_95, "a normal half: (1024 + 0x155) × 2^(13 - 25)"); + assert_eq!(half(0x0200), 2f32.powi(-15), "a subnormal half"); + // Mode 3's first texel: red 65504 and blue 1.5 clip to white, green is 0. + assert_eq!(bc6h(&bc6h_case(3).0, false)[0], [255, 0, 255, 255]); + } + + #[test] + fn any_block_decodes_without_panicking() { + let mut x = 0x9e37_79b9_7f4a_7c15u128 << 64 | 0x2545_f491_4f6c_dd1d; + for _ in 0..20_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let b = x.to_le_bytes(); + let _ = (bc7(&b), bc6h(&b, false), bc6h(&b, true)); + } + } +} diff --git a/crates/dds/src/eac.rs b/crates/dds/src/eac.rs new file mode 100644 index 000000000..fe523c90e --- /dev/null +++ b/crates/dds/src/eac.rs @@ -0,0 +1,107 @@ +//! ETC1 and EAC 4×4 block decoders. +//! +//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping. +//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128. +//! Layout and modifier tables: . + +// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1. +const MODIFIERS: [[i16; 4]; 16] = [ + [2, 5, 8, 14], + [2, 6, 9, 12], + [1, 4, 7, 12], + [1, 3, 5, 12], + [2, 5, 7, 11], + [2, 6, 8, 10], + [3, 6, 7, 10], + [2, 4, 7, 10], + [1, 5, 7, 9], + [1, 4, 7, 9], + [1, 3, 7, 9], + [1, 4, 6, 9], + [2, 3, 6, 9], + [0, 1, 2, 9], + [3, 5, 7, 8], + [2, 4, 6, 8], +]; + +fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) { + let mut first = [0u8; 8]; + let mut second = [0u8; 8]; + for (i, x) in block.iter().enumerate() { + if i < 8 { + first[i] = *x; + } else { + second[i - 8] = *x; + } + } + (first, second) +} + +/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split. +/// Differential bases outside RGB555 are undefined by the format and are refused. +pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]]; + let bits = u64::from_be_bytes(*block); + let differential = bits & (1 << 33) != 0; + let horizontal = bits & (1 << 32) != 0; + let mut bases = [[0i16; 3]; 2]; + for (channel, shift) in [56, 48, 40].into_iter().enumerate() { + let value = ((bits >> shift) & 255) as i16; + let (first, second) = if differential { + let first = value >> 3; + let delta = ((value & 7) ^ 4) - 4; + let second = first + delta; + if !(0..=31).contains(&second) { + return None; + } + ((first << 3) | (first >> 2), (second << 3) | (second >> 2)) + } else { + ((value >> 4) * 17, (value & 15) * 17) + }; + bases[0][channel] = first; + bases[1][channel] = second; + } + let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?; + let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?; + Some(std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let second = if horizontal { y >= 2 } else { x >= 2 }; + let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) }; + let selector = x * 4 + y; + let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] }; + let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude }; + let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8); + [rgb[0], rgb[1], rgb[2], 255] + })) +} + +fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] { + let bits = u64::from_be_bytes(*block); + let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 }; + let scale = (i16::from(block[1] >> 4) * 8).max(1); + let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default(); + std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize; + let magnitude = table.get(selector & 3).copied().unwrap_or_default(); + let modifier = if selector < 4 { -magnitude - 1 } else { magnitude }; + let value = base + modifier * scale; + if signed { + let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default(); + ((value * 255 + 1023) / 2046) as u8 + } else { + let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default(); + ((value * 255 + 1023) / 2047) as u8 + } + }) +} + +pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + channel(block, signed).map(|value| [value, value, value, 255]) +} + +pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + let (red, green) = split_halves(block); + let (red, green) = (channel(&red, signed), channel(&green, signed)); + std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255]) +} diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 4eb8ff994..354067f26 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -39,6 +39,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod bc; +pub mod bptc; +mod eac; +mod packed; +pub mod pixels; use std::borrow::Cow; use std::fmt; @@ -84,6 +88,8 @@ pub enum DdsError { Alloc(usize), /// The decoded output exceeds the caller-selected per-buffer byte limit. LimitExceeded { required: usize, limit: u64 }, + /// Input pixel data ended before the declared dimensions or block count. + Truncated(String), } impl fmt::Display for DdsError { @@ -94,6 +100,7 @@ impl fmt::Display for DdsError { DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"), DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"), DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"), + DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"), } } } diff --git a/crates/dds/src/packed.rs b/crates/dds/src/packed.rs new file mode 100644 index 000000000..6434a6e3c --- /dev/null +++ b/crates/dds/src/packed.rs @@ -0,0 +1,51 @@ +//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits. +//! Unsigned floats: , sections 10.2 and 10.3. + +use crate::bptc; + +pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023; + [channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85] +} + +// These unsigned formats share binary16's five-bit exponent and bias. Padding the +// six- or five-bit fraction with zeroes produces the same value in a positive half. +fn unsigned_float(bits: u16, padding: u32) -> f32 { + bptc::half(bits << padding) +} + +pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding)); + [channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255] +} + +pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + let packed = u32::from_le_bytes(*bytes); + let scale = 2.0f32.powi((packed >> 27) as i32 - 24); + let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale); + [channel(0), channel(9), channel(18), 255] +} + +#[cfg(test)] +mod tests { + use super::unsigned_float; + + #[test] + fn unsigned_float_boundaries_are_preserved_before_display_quantization() { + for (fraction_bits, padding, smallest, largest_subnormal, maximum) in + [(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)] + { + let fractions = 1u16 << fraction_bits; + assert_eq!(unsigned_float(0, padding).to_bits(), 0); + assert_eq!(unsigned_float(1, padding).to_bits(), smallest); + assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal); + assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000); + assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum); + assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY); + assert!(unsigned_float(31 * fractions + 1, padding).is_nan()); + assert!(unsigned_float(32 * fractions - 1, padding).is_nan()); + } + } +} diff --git a/crates/dds/src/pixels.rs b/crates/dds/src/pixels.rs new file mode 100644 index 000000000..8d3933911 --- /dev/null +++ b/crates/dds/src/pixels.rs @@ -0,0 +1,390 @@ +//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts, +//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored. + +use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha}; + +/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture. +pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20; + +/// How a texture's pixels are laid out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PixelLayout { + /// Alpha only (shown as white with that alpha). + Alpha8, + /// One grey channel. + R8, + /// One unsigned 16-bit channel, shown as grey. + R16, + /// Two unsigned 8-bit channels; blue is zero and alpha is opaque. + Rg8, + /// Two unsigned 16-bit channels; blue is zero and alpha is opaque. + Rg16, + /// Three unsigned 16-bit channels; alpha is opaque. + Rgb16, + /// Four unsigned 16-bit channels, including alpha. + Rgba16, + RHalf, + RgHalf, + RgbaHalf, + RFloat, + RgFloat, + RgbaFloat, + /// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB. + Rgb9e5, + /// Packed unsigned 10-bit RGB with two-bit alpha, low bits first. + Rgba1010102, + /// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB. + Rgb111110Float, + Rgb24, + Rgba32, + Argb32, + Bgra32, + Rgb565, + Rgba4444, + Argb4444, + /// BC1 / DXT1. + Dxt1, + /// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel. + Dxt3, + /// BC3 / DXT5. + Dxt5, + /// One channel in blocks (shown as grey). + Bc4, + /// Two channels in blocks, usually a normal map (blue is rebuilt from red and green). + Bc5, + /// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB. + Bc6h, + /// BC6H with signed half floats. + Bc6hSigned, + Bc7, + /// ETC1 RGB, with individual or differential base colours. + Etc1, + /// One EAC channel, shown as grey. + EacR, + /// One signed EAC channel; -1..1 maps to 0..255. + EacRSigned, + /// Two EAC channels; blue is zero and alpha is opaque. + EacRg, + /// Two signed EAC channels; -1..1 maps to 0..255. + EacRgSigned, +} + +/// Bytes of a `width`×`height` picture in `layout`. +pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option { + let (w, h) = (width as usize, height as usize); + let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?; + match layout { + PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h), + PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => { + w.checked_mul(h)?.checked_mul(2) + } + PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3), + PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4), + PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6), + PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8), + PixelLayout::Rgba32 + | PixelLayout::Argb32 + | PixelLayout::Bgra32 + | PixelLayout::RgHalf + | PixelLayout::RFloat + | PixelLayout::Rgb9e5 + | PixelLayout::Rgba1010102 + | PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4), + PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8), + PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16), + PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8), + PixelLayout::Dxt3 + | PixelLayout::Dxt5 + | PixelLayout::Bc5 + | PixelLayout::Bc6h + | PixelLayout::Bc6hSigned + | PixelLayout::Bc7 + | PixelLayout::EacRg + | PixelLayout::EacRgSigned => blocks.checked_mul(16), + } +} + +/// Convert an IEEE 754 binary16 half-float's bits to `f32`. +pub fn half_to_f32(h: u16) -> f32 { + bptc::half(h) +} + +/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip. +pub fn linear_to_srgb8(v: f32) -> u8 { + bptc::srgb8(v) +} + +/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_colour(block, true) +} + +/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row). +pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_values(block).map(|r| [r, r, r, 255]) +} + +/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row). +pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default())); + std::array::from_fn(|k| { + let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0); + let z = (1.0 - x * x - y * y).max(0.0).sqrt(); + [r[k], g[k], ((z + 1.0) * 127.5) as u8, 255] + }) +} + +/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque). +pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bptc::bc6h(block, signed) +} + +/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + bptc::bc7(block) +} + +/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits. +pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + eac::etc1(block) +} + +/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels. +pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + eac::scalar(block, signed) +} + +/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255). +pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + eac::dual(block, signed) +} + +/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb9e5(bytes) +} + +/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8. +pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgba1010102(bytes) +} + +/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb111110(bytes) +} + +fn unorm8(value: u16) -> u8 { + ((u32::from(value) * 255 + 32767) / 65535) as u8 +} + +fn unorm16_pixels(samples: impl Iterator, channels: usize) -> impl Iterator { + let mut samples = samples.map(unorm8); + std::iter::from_fn(move || { + let (r, g) = (samples.next()?, samples.next()?); + let b = if channels > 2 { samples.next()? } else { 0 }; + let a = if channels > 3 { samples.next()? } else { 255 }; + Some([r, g, b, a]) + }) +} + +fn float_pixels(mut samples: impl Iterator, channels: usize) -> impl Iterator { + std::iter::from_fn(move || { + let r = bptc::srgb8(samples.next()?); + if channels == 1 { + return Some([r, r, r, 255]); + } + let g = bptc::srgb8(samples.next()?); + if channels == 2 { + return Some([r, g, 0, 255]); + } + let b = bptc::srgb8(samples.next()?); + let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8; + Some([r, g, b, a]) + }) +} + +fn expand5(v: u16) -> u8 { + let v = (v & 31) as u8; + (v << 3) | (v >> 2) +} + +fn expand6(v: u16) -> u8 { + let v = (v & 63) as u8; + (v << 2) | (v >> 4) +} + +fn rgb565(v: u16) -> [u8; 4] { + [expand5(v >> 11), expand6(v >> 5), expand5(v), 255] +} + +fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] { + order.map(|shift| ((v >> shift) & 15) as u8 * 17) +} + +fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator) { + let across = w.div_ceil(4); + for (i, block) in texels.enumerate() { + let (bx, by) = (i % across, i / across); + for (k, p) in block.iter().enumerate() { + let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4); + if x < w && y < h { + let at = (y * w + x) * 4; + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(p); + } + } + } + } +} + +/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order. +/// +/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget. +pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result, DdsError> { + decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES) +} + +/// Decode into RGBA8, allowing at most `max_bytes` of output. +/// +/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels +/// or reserving the output. +pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result, DdsError> { + let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?; + let (w, h) = (width as usize, height as usize); + let out_len = + w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?; + if out_len as u64 > max_bytes { + return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes }); + } + let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?; + if w == 0 || h == 0 { + return Err(DdsError::Malformed("an empty picture".into())); + } + let mut out: Vec = alloc_zeroed(out_len)?; + let mut put = |px: &mut dyn Iterator| { + for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) { + *dst = p; + } + }; + let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)); + let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)); + match layout { + PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)), + PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)), + PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)), + PixelLayout::RFloat => put(&mut float_pixels(floats, 1)), + PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)), + PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)), + PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)), + PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)), + PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)), + PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])), + PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])), + PixelLayout::R16 => put(&mut u16s.map(|value| { + let grey = unorm8(value); + [grey, grey, grey, 255] + })), + PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])), + PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)), + PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)), + PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)), + PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])), + PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()), + PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])), + PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])), + PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)), + PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))), + PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))), + PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)), + PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)), + PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)), + PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)), + PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)), + PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))), + PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))), + PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)), + PixelLayout::EacR | PixelLayout::EacRSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned))) + } + PixelLayout::EacRg | PixelLayout::EacRgSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned))) + } + PixelLayout::Etc1 => { + let mut valid = true; + let texels = data.as_chunks::<8>().0.iter().map_while(|block| { + let pixels = eac::etc1(block); + valid &= pixels.is_some(); + pixels + }); + place_blocks(&mut out, w, h, texels); + if !valid { + return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into())); + } + } + } + Ok(out) +} + +/// Flip a `width`-wide RGBA8 picture upside down. +pub fn flip_rows(rgba: &[u8], width: u32) -> Vec { + let row = (width as usize).saturating_mul(4).max(1); + rgba.chunks(row).rev().flatten().copied().collect() +} + +#[cfg(test)] +mod tests { + use super::{PixelLayout, decode, decode_with_limit, flip_rows, size}; + use crate::DdsError; + + #[test] + fn uncompressed_and_swizzled_layouts() { + assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]); + assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]); + assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]); + assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]); + assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_)))); + assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_)))); + assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. }))); + } + + #[test] + fn block_and_packed_layouts_crop_partial_blocks() { + assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32)); + assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100); + // DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0. + let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap(); + assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..])); + // DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255). + let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0]; + b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]); + let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap(); + assert_eq!((px[3], px[7]), (0, 255)); + // BC4 & BC5. + assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]); + let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0]; + n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]); + assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]); + // Packed RGB9E5 & RGBA1010102. + let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]); + let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]); + } +} diff --git a/crates/dds/tests/known_answers.rs b/crates/dds/tests/known_answers.rs new file mode 100644 index 000000000..ce6e5e9f0 --- /dev/null +++ b/crates/dds/tests/known_answers.rs @@ -0,0 +1,114 @@ +//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs) +//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed). + +use craft_dds::DdsError; +use craft_dds::pixels::{self, PixelLayout}; + +#[test] +fn bc7_mode6_known_bitstream() { + // Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices): + // e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4. + let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44]; + let texels = pixels::decode_bc7_block(&block); + assert_eq!(texels[0], [241, 121, 21, 255]); + assert_eq!(texels[1], [40, 200, 254, 128]); + assert_eq!(texels[2], [134, 163, 145, 188]); + assert_eq!(texels[3], [188, 142, 83, 221]); + + // Reserved mode (low byte 0x00) decodes to all zeroes. + assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]); + + // Cropped 3x2 image keeps the top-left 3x2 texels in row-major order. + let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap(); + assert_eq!(rgba.len(), 3 * 2 * 4); + assert_eq!(&rgba[..4], &[241, 121, 21, 255]); + assert_eq!(&rgba[4..8], &[40, 200, 254, 128]); + assert_eq!(&rgba[8..12], &[134, 163, 145, 188]); +} + +#[test] +fn bc6h_unsigned_and_signed_known_bitstreams() { + // Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices): + // e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8. + let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + let unsigned = pixels::decode_bc6h_block(&block, false); + assert_eq!(unsigned[0], [228, 105, 7, 255]); + assert_eq!(unsigned[1], [7, 228, 105, 255]); + assert_eq!(unsigned[2], [51, 160, 39, 255]); + + let signed_pos = pixels::decode_bc6h_block(&block, true); + assert_eq!(signed_pos[0], [255, 255, 105, 255]); + assert_eq!(signed_pos[1], [105, 255, 255, 255]); + assert_eq!(signed_pos[2], [255, 255, 255, 255]); + + // Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338). + // Negative linear values clip to 0 in sRGB8 output. + let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let signed_neg = pixels::decode_bc6h_block(&neg_block, true); + assert_eq!(signed_neg[0], [0, 105, 255, 255]); + assert_eq!(signed_neg[1], [105, 0, 255, 255]); + assert_eq!(signed_neg[2], [0, 0, 255, 255]); + + let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap(); + assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]); + let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap(); + assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]); +} + +#[test] +fn etc1_known_bitstreams_and_invalid_differential() { + // Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5. + let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&individual).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3). + let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&differential).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential base + delta outside 0..=31 must be rejected. + let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00]; + assert!(pixels::decode_etc1_block(&invalid).is_none()); + assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_)))); +} + +#[test] +fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() { + // Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128. + let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]); + + // Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58. + let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]); + + // Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125). + let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00]; + let col_texels = pixels::decode_eac_r_block(&eac_col, false); + assert_eq!(col_texels[1], [142, 142, 142, 255]); + assert_eq!(col_texels[0], [125, 125, 125, 255]); + assert_eq!(col_texels[4], [125, 125, 125, 255]); + + // Dual-channel EAC_RG (unsigned and signed): R then G. + let mut eac_rg_u = [0u8; 16]; + eac_rg_u[..8].copy_from_slice(&eac_r_u); + eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4)); + + let mut eac_rg_s = [0u8; 16]; + eac_rg_s[..8].copy_from_slice(&eac_r_s); + eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4)); +} diff --git a/crates/design-lint/src/workspace.rs b/crates/design-lint/src/workspace.rs index 80d4f53f8..5425859d0 100644 --- a/crates/design-lint/src/workspace.rs +++ b/crates/design-lint/src/workspace.rs @@ -137,6 +137,9 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[ const NO_GLOBAL_STATE: &[(&str, &str)] = &[ // The trait's home crate: it implements `MemoProps` by hand for std and framework value types. ("crates/ui-contract/src/contract/memo.rs", "MemoProps"), + // Settled fact: `ModalRules` holds a closure the derive cannot take; it keys on its plain fields and the revision + // the app moves with every rule change, which stands for the closure. + ("crates/menu/src/modal.rs", "MemoProps"), // Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init. ("crates/ui-contract/src/fonts/defaults.rs", "HACK"), ("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"), diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index bc859ea5f..6d7885983 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true workspace = true [dependencies] +craft-color-transform = { workspace = true } craft-develop-model = { workspace = true } serde = { workspace = true } @@ -20,3 +21,4 @@ rayon = { workspace = true } [dev-dependencies] craft-render-parity = { workspace = true } proptest = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md index 92f543eb3..6cab63428 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -12,9 +12,11 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = ", - ys: Vec, - ms: Vec, -} - -impl MonotoneCurve { - /// Build from points; sorts by x, merges duplicates. Fewer than two points → identity. - pub fn new(points: &[(f64, f64)]) -> MonotoneCurve { - let mut p: Vec<(f64, f64)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); - p.sort_by(|a, b| a.0.total_cmp(&b.0)); - p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9); - if p.len() < 2 { - p = vec![(0.0, 0.0), (1.0, 1.0)]; - } - let n = p.len(); - let xs: Vec = p.iter().map(|q| q.0).collect(); - let ys: Vec = p.iter().map(|q| q.1).collect(); - let d: Vec = (0..n - 1).map(|i| (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i])).collect(); - let mut ms = vec![0.0; n]; - ms[0] = d[0]; - ms[n - 1] = d[n - 2]; - for i in 1..n - 1 { - ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 }; - } - // Fritsch–Carlson limiter where the data is monotone within a segment. - for i in 0..n - 1 { - if d[i] == 0.0 { - ms[i] = 0.0; - ms[i + 1] = 0.0; - continue; - } - let a = ms[i] / d[i]; - let b = ms[i + 1] / d[i]; - let s = a * a + b * b; - if s > 9.0 { - let t = 3.0 / s.sqrt(); - ms[i] = t * a * d[i]; - ms[i + 1] = t * b * d[i]; - } - } - MonotoneCurve { xs, ys, ms } - } - - pub fn identity() -> MonotoneCurve { - MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)]) - } - - pub fn eval(&self, x: f64) -> f64 { - // NaN passes both bound checks below and would send the search past either end - if x.is_nan() { - return x; - } - let n = self.xs.len(); - if x <= self.xs[0] { - return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0; - } - if x >= self.xs[n - 1] { - return self.ys[n - 1]; - } - let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) { - Ok(i) => return self.ys[i], - Err(i) => i - 1, - }; - let h = self.xs[i + 1] - self.xs[i]; - let t = (x - self.xs[i]) / h; - let (t2, t3) = (t * t, t * t * t); - (2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[i] - + (t3 - 2.0 * t2 + t) * h * self.ms[i] - + (-2.0 * t3 + 3.0 * t2) * self.ys[i + 1] - + (t3 - t2) * h * self.ms[i + 1] - } - - /// Sample into a LUT of `n` entries (at least 2) over `0..1`. - pub fn to_lut(&self, n: usize) -> Lut1 { - let n = n.max(2); - Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() } - } - - pub fn points(&self) -> Vec<(f64, f64)> { - self.xs.iter().copied().zip(self.ys.iter().copied()).collect() - } -} - -/// A 1-D lookup table over `0..1` with linear interpolation; inputs outside clamp. -#[derive(Clone, Debug, PartialEq)] -pub struct Lut1 { - pub v: Vec, -} - -impl Lut1 { - /// At least 2 entries, like [`Lut1::from_fn`]. - pub fn identity(n: usize) -> Lut1 { - Lut1::from_fn(n, |x| x) - } - /// `f` sampled at `n` evenly spaced points over `0..1` (at least 2). - pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 { - let n = n.max(2); - Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() } - } - /// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0). - #[inline] - pub fn eval(&self, x: f32) -> f32 { - let x = x.clamp(0.0, 1.0); - let n = self.v.len(); - if n < 2 { - return self.v.first().copied().unwrap_or(x); - } - let f = x * (n - 1) as f32; - let i = (f as usize).min(n - 2); - let t = f - i as f32; - self.v[i] + (self.v[i + 1] - self.v[i]) * t - } - /// `self ∘ inner` (apply `inner` first). - pub fn compose(&self, inner: &Lut1) -> Lut1 { - Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() } - } - pub fn is_identity(&self) -> bool { - let n = self.v.len(); - self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn identity_curve() { - let c = MonotoneCurve::identity(); - for i in 0..=10 { - let x = i as f64 / 10.0; - assert!((c.eval(x) - x).abs() < 1e-12); - } - assert!(c.to_lut(256).is_identity()); - } - - #[test] - fn passes_through_points_and_is_monotone() { - let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)]; - let c = MonotoneCurve::new(&pts); - for (x, y) in pts { - assert!((c.eval(x) - y).abs() < 1e-12); - } - let mut prev = -1.0; - for i in 0..=1000 { - let y = c.eval(i as f64 / 1000.0); - assert!(y >= prev - 1e-12); - prev = y; - } - } - - #[test] - fn no_overshoot_on_flat_segment() { - let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]); - for i in 400..=600 { - let y = c.eval(i as f64 / 1000.0); - assert!((y - 0.5).abs() < 1e-9, "{y}"); - } - } - - #[test] - fn lut_compose() { - let a = Lut1::from_fn(1024, |x| x * x); - let b = Lut1::from_fn(1024, |x| x.sqrt()); - let c = a.compose(&b); - assert!((c.eval(0.3) - 0.3).abs() < 2e-3); - } - - #[test] - fn nan_input_and_short_luts_do_not_panic() { - let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]); - assert!(c.eval(f64::NAN).is_nan()); - assert!(c.eval(-f64::NAN).is_nan()); - for n in [0, 1] { - assert_eq!(c.to_lut(n).v.len(), 2, "{n}"); - assert!(Lut1::identity(n).is_identity(), "{n}"); - assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}"); - } - assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3); - assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table"); - assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0); - assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7); - } - - proptest::proptest! { - #[test] - fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) { - let mut ys = ys; ys.sort_by(|a, b| a.total_cmp(b)); - let n = ys.len(); - let pts: Vec<(f64, f64)> = ys.iter().enumerate().map(|(i, y)| (i as f64 / (n - 1) as f64, *y)).collect(); - let c = MonotoneCurve::new(&pts); - let mut prev = f64::MIN; - for i in 0..=200 { let y = c.eval(i as f64 / 200.0); proptest::prop_assert!(y >= prev - 1e-9); prev = y; } - } - } -} diff --git a/crates/develop/src/finish.rs b/crates/develop/src/finish.rs new file mode 100644 index 000000000..c826510fa --- /dev/null +++ b/crates/develop/src/finish.rs @@ -0,0 +1,235 @@ +//! Pure-Rust finishing-stage helpers: sharpening masks/limits, vignette parameters, value film +//! grain, gamut mapping, and curve saturation refinement. + +use craft_develop_model::{DevelopSettings, VignetteStyle}; + +#[inline] +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How much of the sharpening a pixel gets (`0..1`) under Masking `masking` (`0..1`), from its +/// fine detail `det` (log luminance minus its texture blur): `1` everywhere at `0`, only stronger +/// edges as it rises. +#[inline] +pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } +} + +/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview. +#[inline] +pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 } +} + +/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail. +pub const SHARPEN_GAIN: f32 = 7.0; + +/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: `0.03` stops (large +/// edge detail is flattened so halos stay small) up to `1.5` stops (practically linear). +pub fn sharpen_limit(detail: f64) -> f32 { + let d = (detail / 100.0).clamp(0.0, 1.0) as f32; + 0.03 * 50f32.powf(d) +} + +/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the +/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge +/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone. +#[inline] +pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 { + let m = pixel_sharpen_mask_weight(mask, det); + SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit) +} + +/// Vignette (post-crop) parameters. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Vig { + pub amount: f32, + pub start: f32, + pub width: f32, + pub aspect_mix: f32, + pub power: f32, + pub highlights: f32, + pub style: VignetteStyle, +} + +/// Resolve post-crop vignette parameters from `s`, returning `None` when `s.vignette.amount == 0.0`. +pub fn vignette(s: &DevelopSettings) -> Option { + let v = &s.vignette; + (v.amount != 0.0).then(|| { + let r = (v.roundness / 100.0) as f32; + Vig { + amount: (v.amount / 100.0) as f32, + start: 0.15 + (v.midpoint / 100.0) as f32 * 0.95, + width: 0.05 + (v.feather / 100.0) as f32 * 1.1, + aspect_mix: ((r + 1.0) / 2.0).clamp(0.0, 1.0), + power: if r >= 0.0 { 2.0 } else { 2.0 + (-r) * 6.0 }, + highlights: (v.highlights / 100.0) as f32, + style: v.style, + } + }) +} + +/// Hash constants of [`grain_noise`] (shared with the GPU kernel). +pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995]; + +/// The grain of processes V1 to V6: two octaves of value noise. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueGrain { + /// Amplitude (display-encoded). + pub amt: f32, + /// Noise cell size (output pixels). + pub cell: f32, + /// Roughness `0..1`: weight of the finer octave. + pub rough: f32, + pub seed: u32, +} + +/// Resolve [`ValueGrain`] parameters from `s` at `px_per_long` output pixels per long edge, +/// returning `None` when `s.grain.amount <= 0.0`. +pub fn value_grain(s: &DevelopSettings, px_per_long: f64) -> Option { + let g = &s.grain; + (g.amount > 0.0).then(|| { + let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32; + ValueGrain { amt: (g.amount / 100.0) as f32 * 0.13, cell: cell.max(0.6), rough: (g.roughness / 100.0) as f32, seed: g.seed } + }) +} + +/// Smooth value noise in `-1..1` at `(x, y)` for `seed`. Non-finite coordinates return `0.0`. +#[inline] +pub fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { + if !x.is_finite() || !y.is_finite() { + return 0.0; + } + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let h = |i: i32, j: i32| { + let mut v = (i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ seed.wrapping_mul(GRAIN_HASH[2]); + v ^= v >> 13; + v = v.wrapping_mul(GRAIN_HASH[3]); + v ^= v >> 15; + (v & 0xffff) as f32 / 32768.0 - 1.0 + }; + let (i, j) = (x0 as i32, y0 as i32); + let (u, v) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy)); + let a = h(i, j) + (h(i + 1, j) - h(i, j)) * u; + let b = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * u; + a + (b - a) * v +} + +/// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for +/// the gamut warnings (tolerates rounding at the gamut boundary). +pub const GAMUT_WARN: f32 = 0.995; + +/// Desaturate linear `r` towards its luminance (weights `luma`) until every channel is in `0..=1`; +/// returns the mapped colour and the chroma scale used (`1.0` = already in gamut). +#[inline] +pub fn gamut_map(r: [f32; 3], luma: [f32; 3]) -> ([f32; 3], f32) { + gamut_map_to(r, luma, 1.0) +} + +/// [`gamut_map`] into `0..=peak` (an HDR render's range; `peak = 1.0` is [`gamut_map`]). +#[inline] +pub fn gamut_map_to(r: [f32; 3], luma: [f32; 3], peak: f32) -> ([f32; 3], f32) { + let yy = (luma[0] * r[0] + luma[1] * r[1] + luma[2] * r[2]).clamp(0.0, peak); + let mut t = 1.0f32; + for c in r { + if c < 0.0 { + t = t.min(yy / (yy - c).max(1e-9)); + } else if c > peak { + t = t.min((peak - yy) / (c - yy).max(1e-9)); + } + } + if t < 1.0 { (r.map(|c| yy + (c - yy) * t), t) } else { (r, 1.0) } +} + +/// Refine Saturation: scale the curved colour's chroma (around its luma, encoded values) so its +/// saturation (chroma / luma) moves from the curve's towards the pre-curve one: the ratio is +/// `(s_curve / s_before)^refine`, so `1` keeps the curve and `0` restores the original saturation. +#[inline] +pub fn refine_saturation(before: [f32; 3], after: [f32; 3], refine: f32) -> [f32; 3] { + let luma = |e: [f32; 3]| 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; + let chroma = |e: [f32; 3]| e[0].max(e[1]).max(e[2]) - e[0].min(e[1]).min(e[2]); + let (y0, y1) = (luma(before), luma(after)); + let s0 = chroma(before) / y0.max(1e-4); + let s1 = chroma(after) / y1.max(1e-4); + if s1 <= 1e-6 || s0 <= 1e-6 { + return after; + } + let k = (s0 / s1).powf(1.0 - refine).clamp(0.0, 4.0); + after.map(|v| y1 + (v - y1) * k) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sharpen_helpers_behave_smoothly_and_bound_detail() { + assert_eq!(sharpen_mask_weight(0.0, 0.0), 1.0); + assert_eq!(pixel_sharpen_mask_weight(0.0, 0.0), 1.0); + assert_eq!(sharpen_mask_weight(0.8, 0.0), 0.0); + assert!(sharpen_mask_weight(0.8, 1.0) == 1.0); + assert!((sharpen_limit(0.0) - 0.03).abs() < 1e-6); + assert!((sharpen_limit(100.0) - 1.5).abs() < 1e-4); + let lim = sharpen_limit(50.0); + assert!(sharpen_term(0.0, lim, 0.0) == 0.0); + assert!(sharpen_term(10.0, lim, 0.0) < SHARPEN_GAIN * lim); + assert!(sharpen_term(0.1, lim, 0.0) > 0.0); + } + + #[test] + fn vignette_resolves_only_when_nonzero() { + let mut s = DevelopSettings::default(); + assert!(vignette(&s).is_none()); + s.vignette.amount = -50.0; + s.vignette.roundness = -100.0; + let v = vignette(&s).unwrap(); + assert!((v.amount - -0.5).abs() < 1e-6); + assert!((v.power - 8.0).abs() < 1e-6); + assert!((v.aspect_mix - 0.0).abs() < 1e-6); + } + + #[test] + fn grain_is_bounded_and_handles_non_finite_coords() { + let mut s = DevelopSettings::default(); + assert!(value_grain(&s, 2000.0).is_none()); + s.grain.amount = 50.0; + s.grain.size = 25.0; + s.grain.roughness = 50.0; + let g = value_grain(&s, 2000.0).unwrap(); + assert!(g.amt > 0.0 && g.cell >= 0.6); + assert_eq!(grain_noise(f32::NAN, 1.0, 7), 0.0); + assert_eq!(grain_noise(1.0, f32::INFINITY, 7), 0.0); + for i in 0..20 { + let n = grain_noise(i as f32 * 0.37, i as f32 * 0.71, g.seed); + assert!((-1.0..=1.0).contains(&n), "{n}"); + } + } + + #[test] + fn gamut_map_clamps_out_of_gamut_towards_luma() { + let luma = [0.2126, 0.7152, 0.0722]; + let (in_gamut, t0) = gamut_map([0.2, 0.5, 0.8], luma); + assert_eq!(in_gamut, [0.2, 0.5, 0.8]); + assert_eq!(t0, 1.0); + + let (mapped, t1) = gamut_map([1.5, -0.2, 0.3], luma); + assert!(t1 < GAMUT_WARN); + assert!(mapped.iter().all(|&c| (-1e-6..=1.0 + 1e-6).contains(&c)), "{mapped:?}"); + + let (hdr, t2) = gamut_map_to([2.5, 0.5, 0.5], luma, 4.0); + assert_eq!(hdr, [2.5, 0.5, 0.5]); + assert_eq!(t2, 1.0); + } + + #[test] + fn refine_saturation_interpolates_between_original_and_curved() { + let before = [0.4, 0.2, 0.1]; + let after = [0.6, 0.3, 0.15]; + assert_eq!(refine_saturation(before, after, 1.0), after); + let neutral = refine_saturation([0.3, 0.3, 0.3], [0.5, 0.5, 0.5], 0.5); + assert_eq!(neutral, [0.5, 0.5, 0.5]); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index da88b48c6..e3099235c 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -5,5 +5,7 @@ pub mod color; pub mod curve; +pub mod finish; pub mod inpaint; pub mod lut; +pub mod tone; diff --git a/crates/develop/src/tone.rs b/crates/develop/src/tone.rs new file mode 100644 index 000000000..0ff62fce4 --- /dev/null +++ b/crates/develop/src/tone.rs @@ -0,0 +1,696 @@ +//! The global tone map: scene luminance → display-linear luminance. +//! +//! Built in the log domain around middle grey (0.18): contrast scales log-exposure about grey, +//! whites move the shoulder (white point), blacks move the toe. The shoulder is an extended +//! Reinhard curve so highlights roll off smoothly instead of clipping. +//! +//! Rendered (display-referred) sources such as JPEGs use [`ToneMap::display`] instead: identity at +//! neutral settings (an unedited JPEG renders exactly as the file), with contrast/whites/blacks as +//! S-curve adjustments in a gamma-2.2 perceptual domain and a short shoulder above 0.95. + +pub const GREY: f32 = 0.18; +/// The tone LUT spans `LUT_MIN_EV..LUT_MAX_EV` around grey in `LUT_N` steps. +pub const LUT_MIN_EV: f32 = -14.0; +pub const LUT_MAX_EV: f32 = 10.0; +pub const LUT_N: usize = 4096; +/// Nodes of a camera chroma curve, evenly spaced over display luminance 0..=1. +pub const CHROMA_N: usize = 8; +const NO_CHROMA: [f32; CHROMA_N] = [1.0; CHROMA_N]; + +/// A file-local camera look, fitted independently of the scene-linear colour transform. +/// Knots are scene/display-linear luminance pairs. Keeping this in the finish stage preserves +/// RAW exposure and highlight headroom; it is never baked into the decoded sensor pixels. +/// `chroma` scales colourfulness by display luminance after the curve (a camera's per-channel +/// curve saturates shadows and bleaches highlights toward white, which a luminance curve can't). +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +pub struct CameraTone { + knots: [[f32; 2]; 32], + chroma: [f32; CHROMA_N], +} + +impl<'de> serde::Deserialize<'de> for CameraTone { + fn deserialize>(d: D) -> Result { + #[derive(serde::Deserialize)] + struct Wire { + knots: [[f32; 2]; 32], + // absent in smart previews written before the chroma curve existed + #[serde(default)] + chroma: Option<[f32; CHROMA_N]>, + } + let w = Wire::deserialize(d)?; + let tone = Self::new(w.knots).ok_or_else(|| serde::de::Error::custom("invalid camera tone curve"))?; + match w.chroma { + Some(c) => tone.with_chroma(c).ok_or_else(|| serde::de::Error::custom("invalid camera chroma curve")), + None => Ok(tone), + } + } +} + +impl CameraTone { + pub fn new(knots: [[f32; 2]; 32]) -> Option { + let mut previous = [0.0, 0.0]; + for p in knots { + if !p.iter().all(|v| v.is_finite()) || p[0] <= previous[0] || p[1] < previous[1] || p[1] >= 1.0 { + return None; + } + previous = p; + } + Some(Self { knots, chroma: NO_CHROMA }) + } + + /// The curve with chroma scales at display luminance 0, 1/7 … 1 (each finite, 0..=4). + pub fn with_chroma(self, chroma: [f32; CHROMA_N]) -> Option { + chroma.iter().all(|k| k.is_finite() && (0.0..=4.0).contains(k)).then_some(Self { chroma, ..self }) + } + + pub fn chroma(&self) -> &[f32; CHROMA_N] { + &self.chroma + } + + /// The (scene, display) luminance knots, in increasing order. + pub fn knots(&self) -> &[[f32; 2]; 32] { + &self.knots + } + + pub fn apply(&self, y: f32) -> f32 { + if !y.is_finite() || y <= 0.0 { + return 0.0; + } + let mut previous = [0.0, 0.0]; + for p in self.knots { + if y <= p[0] { + let t = (y - previous[0]) / (p[0] - previous[0]); + return previous[1] + t * (p[1] - previous[1]); + } + previous = p; + } + let a = self.knots[30]; + let b = self.knots[31]; + // Extend beyond observed (unclipped) highlights with a continuous, bounded shoulder. + let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0); + 1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp() + } + + /// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is + /// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the + /// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`] + /// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a + /// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white. + /// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the + /// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving + /// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last + /// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the + /// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white. + pub fn apply_rolloff(&self, y: f32) -> f32 { + let (a, b) = (self.knots[30], self.knots[31]); + if !y.is_finite() || y <= b[0] { + return self.apply(y); + } + // the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the + // knots non-decreasing, so it is at least 0) + let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0); + // `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one + // would step the curve down past a knot within it of white) + rolloff_past(y, b, slope, CAMERA_MIN_SLOPE) + } +} + +/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene +/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last +/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that +/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below +/// white. +const CAMERA_MIN_SLOPE: f32 = 0.1; + +/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts +/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at +/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0 +/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by +/// Exposure +1 (issue #1632). +pub const ROLLOFF_STOPS: f32 = 1.0; + +/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the +/// curve rises at `slope` (display per unit of scene luminance): the gap to white is +/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`, +/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the +/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the +/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`) +/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and +/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still +/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a +/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it. +/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in +/// `f32` the gap rounds to 0 eventually. +fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 { + let gap = 1.0 - o; + let k = 1.0 / ROLLOFF_STOPS; + // bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps + let per = |s: f32| (s * x / (gap * k)).min(1e30); + let c = per(slope); + let d = (per(min_slope) - c).max(0.0); + let u = (k * (y / x).log2()).exp2() - 1.0; + // each term only when its coefficient is positive: `0 · ∞` is NaN far up + let linear = if c > 0.0 { c * u } else { 0.0 }; + let floor = if d > 0.0 { d * past_join(u) } else { 0.0 }; + 1.0 - gap / (1.0 + linear + floor) +} + +/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite +/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`. +fn past_join(u: f32) -> f32 { + if u.is_infinite() { + return u; + } + let u = f64::from(u); + (u - u.ln_1p()).max(0.0) as f32 +} + +/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`]) +/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at +/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about +/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at +/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632). +pub const GENERIC_KNEE_STOPS: f32 = 0.5; + +/// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve. +const HDR_FROM_EV: f32 = 1.5; + +#[derive(Clone, Debug)] +pub struct ToneMap { + lut: Vec, + chroma: [f32; CHROMA_N], +} + +impl ToneMap { + pub fn camera(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::camera_hdr(curve, contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::camera`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR + /// exactly): the camera's look up to 1.5 EV over grey, so midtones match the SDR render (and a + /// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in + /// [`ToneMap::hdr`]. + pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak) + } + + /// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops + /// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's. + pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak) + } + + fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let adjustment = Self::display(contrast, whites, blacks); + let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0; + let top = (2.9 - 1.6 * (whites as f32 / 100.0) + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5); + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = curve(GREY * 2f32.powf(ev)); + let o = if neutral { y } else { adjustment.apply(y) }; + if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o } + }) + .collect(); + ToneMap { lut, chroma } + } + /// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units). + pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::hdr(contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::new`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR exactly). + /// Below about half of SDR white the curve is the SDR one; above, the highlights gain up to + /// `peak − 1` more along a smoothstep in scene EV, from 1.5 EV over grey to one stop past the + /// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`, + /// and reaches it there (within the table's range). + pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, false) + } + + /// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white + /// point the curve rolls off into white in stops, with the same value and slope at the join, + /// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR + /// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for + /// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`]. + pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, true) + } + + fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let c = (contrast / 100.0) as f32; + let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c }; + // White point: scene luminance (after contrast) that maps to display 1.0. + let white_ev = 2.9 - 1.6 * (whites as f32 / 100.0); + let wl = GREY * 2f32.powf(white_ev); + let pre = 1.0 + GREY / wl; // keep grey near grey + let b = (blacks / 100.0) as f32; + // extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl + let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y); + // V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)² + let knee = wl * (-GENERIC_KNEE_STOPS).exp2(); + let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee)); + let knee = [knee, reinhard(knee)]; + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = GREY * 2f32.powf(ev * slope) * pre; + let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) }; + o = o.min(1.0); + // Toe: blacks < 0 crushes, > 0 lifts. + if b < 0.0 { + // Smooth max(0, o − k) (a soft knee), renormalized so 1 stays 1. + let k = -b * 0.035; + let e = 0.004; + let soft = |v: f32| ((v - k) + ((v - k) * (v - k) + e * e).sqrt()) * 0.5; + o = (soft(o) - soft(0.0)) / (soft(1.0) - soft(0.0)); + } else if b > 0.0 { + let k = b * 0.03; + o = k + (1.0 - k) * o; + } + if peak > 1.0 { + let top = (white_ev + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5); + o += (peak - 1.0) * smooth(HDR_FROM_EV, top, ev * slope); + } + o.clamp(0.0, peak) + }) + .collect(); + ToneMap { lut, chroma: NO_CHROMA } + } + + /// Tone map for display-referred sources: identity at neutral settings. + pub fn display(contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::display_hdr(contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::display`] for an HDR render reaching `peak`: values above SDR white (an HDR + /// source, e.g. a decoded gain-map image) pass through and roll off softly towards `peak` + /// instead of clipping at 1; SDR sources (≤ 1) render as with [`ToneMap::display`]. + pub fn display_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let c = (contrast / 100.0) as f32; + let w = (whites / 100.0) as f32; + let b = (blacks / 100.0) as f32; + let m = GREY.powf(1.0 / 2.2); + // Neutral sliders are the identity up to white (issue #1945): the SDR shoulder below would + // pull 1.0 down to 0.9875 (8-bit 255 to 254), so it only shapes an edited curve. + let neutral = c == 0.0 && w == 0.0 && b == 0.0; + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = GREY * 2f32.powf(ev); + let mut p = y.powf(1.0 / 2.2); + if p <= 1.0 { + // S-curve anchored at 0, grey and 1 + p += c * 0.35 * (p - m) * (1.0 - (2.0 * p - 1.0).powi(2)); + // whites: lift/lower the upper tones; blacks: the lower tones + let up = smooth(0.45, 1.0, p); + p += w * 0.12 * up * (1.0 - p * 0.5); + let lo = 1.0 - smooth(0.0, 0.45, p); + p += b * 0.07 * lo * (p * 2.0).min(1.0); + } else { + p += w * 0.12 * 0.5; + } + let mut o = p.max(0.0).powf(2.2); + // short shoulder (SDR, edited curves): slope 1 at 0.95, reaching 1.0 at 1.05 + if peak > 1.0 && o > 0.95 { + // exponential shoulder: slope 1 at 0.95, asymptote at `peak` + let r = peak - 0.95; + o = 0.95 + r * (1.0 - (-(o - 0.95) / r).exp()); + } else if o > 0.95 && !neutral { + let d = (o - 0.95).min(0.1); + o = 0.95 + d - d * d / 0.2; + } + o.clamp(0.0, peak) + }) + .collect(); + ToneMap { lut, chroma: NO_CHROMA } + } + + /// The table (`LUT_N` entries, see [`ToneMap::apply`]). + pub fn lut(&self) -> &[f32] { + &self.lut + } + + /// The chroma curve (`CHROMA_N` entries, see [`ToneMap::chroma_scale`]). + pub fn chroma_lut(&self) -> &[f32] { + &self.chroma + } + + /// Chroma scale at display luminance `o` (exactly 1 everywhere unless a camera look sets it). + #[inline] + pub fn chroma_scale(&self, o: f32) -> f32 { + if !o.is_finite() { + return 1.0; + } + let f = o.clamp(0.0, 1.0) * (CHROMA_N - 1) as f32; + let i = (f as usize).min(CHROMA_N - 2); + let t = f - i as f32; + let (a, b) = (self.chroma.get(i).copied().unwrap_or(1.0), self.chroma.get(i + 1).copied().unwrap_or(1.0)); + if a == b { a } else { a + (b - a) * t } + } + + /// Scene luminance → display-linear luminance. + #[inline] + pub fn apply(&self, y: f32) -> f32 { + if y <= 0.0 { + return 0.0; + } + let ev = (y / GREY).log2(); + let f = ((ev - LUT_MIN_EV) / (LUT_MAX_EV - LUT_MIN_EV)).clamp(0.0, 1.0) * (LUT_N - 1) as f32; + let i = (f as usize).min(LUT_N - 2); + let t = f - i as f32; + let v = self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t; + if ev < LUT_MIN_EV { v * (y / (GREY * 2f32.powf(LUT_MIN_EV))) } else { v } + } +} + +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn knots() -> [[f32; 2]; 32] { + std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + }) + } + + #[test] + fn chroma_curve_is_identity_unless_set_and_survives_serde() { + let plain = CameraTone::new(knots()).unwrap(); + let map = ToneMap::camera(&plain, 0.0, 0.0, 0.0); + assert!([0.0, 0.3, 0.77, 1.0, 2.0].iter().all(|o| map.chroma_scale(*o) == 1.0)); + assert!([0.0, 0.5, 1.0].iter().all(|o| ToneMap::new(0.0, 0.0, 0.0).chroma_scale(*o) == 1.0)); + // smart previews written before the chroma curve existed still load (identity) + let old = serde_json::json!({ "knots": knots() }); + assert_eq!(serde_json::from_value::(old).unwrap(), plain); + let tone = plain.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap(); + let back: CameraTone = serde_json::from_value(serde_json::to_value(tone).unwrap()).unwrap(); + assert_eq!(back, tone); + let map = ToneMap::camera(&tone, 0.0, 0.0, 0.0); + assert!((map.chroma_scale(0.0) - 1.4).abs() < 1e-6 && (map.chroma_scale(1.0) - 0.2).abs() < 1e-6); + assert!((map.chroma_scale(0.5 / 7.0) - 1.35).abs() < 1e-5, "interpolates between nodes"); + assert_eq!(map.chroma_scale(f32::NAN), 1.0); + // hostile values are rejected, also when deserialized + assert!(plain.with_chroma([f32::NAN; CHROMA_N]).is_none()); + assert!(plain.with_chroma([-1.0; CHROMA_N]).is_none()); + let bad = serde_json::json!({ "knots": knots(), "chroma": [9.0, 1, 1, 1, 1, 1, 1, 1] }); + assert!(serde_json::from_value::(bad).is_err()); + } + + #[test] + fn camera_curve_preserves_black_and_extends_headroom() { + let knots = std::array::from_fn(|i| { + let x = 0.005 * 1.15f32.powi(i as i32); + [x, 1.0 - (-3.0 * x).exp()] + }); + let curve = CameraTone::new(knots).unwrap(); + let base = ToneMap::camera(&curve, 0.0, 0.0, 0.0); + assert_eq!(base.apply(0.0), 0.0); + assert!(base.apply(0.1) < base.apply(0.2)); + let mut previous = 0.0; + for i in 0..2000 { + let y = 1e-6 * 1.01f32.powi(i); + let v = base.apply(y); + assert!((0.0..=1.0).contains(&v)); + assert!(v >= previous - 1e-6); + previous = v; + } + assert!((base.apply(0.1) - curve.apply(0.1)).abs() < 0.001); + assert!(ToneMap::camera(&curve, 50.0, 0.0, 0.0).apply(0.3) > base.apply(0.3)); + let mut invalid = knots; + invalid[1][0] = invalid[0][0]; + assert!(CameraTone::new(invalid).is_none()); + assert!(serde_json::from_value::(serde_json::json!({"knots": invalid})).is_err()); + } + + #[test] + fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + let curve = CameraTone::new(knots()).unwrap(); + let last = curve.knots()[31]; + // the camera's curve up to the last knot + for i in 0..200 { + let y = last[0] * i as f32 / 199.0; + assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}"); + } + // continuous, with the slope of the last segment, at the knot + let a = curve.knots()[30]; + let slope = (last[1] - a[1]) / (last[0] - a[0]); + let h = last[0] * 1e-3; + let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + // monotone, below white, and slower to close on it than the V1/V2 extension + let mut previous = last[1]; + for i in 1..3000 { + let y = last[0] * 1.005f32.powi(i); + let o = curve.apply_rolloff(y); + assert!(o >= previous && o < 1.0, "{y}: {o}"); + assert!(o <= curve.apply(y) + 1e-6, "{y}"); + previous = o; + } + assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0))); + // a steep last segment joins with its own slope, and a last knot next to white without a step + for top in [0.9, 0.99995, 1.0 - f32::EPSILON] { + let mut k = knots(); + k[31] = [k[30][0] * 1.01, top]; + let c = CameraTone::new(k).unwrap(); + let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]); + assert!(slope > 16.0 || top < 0.99, "{slope}"); + let mut prev = c.apply_rolloff(k[31][0]); + assert_eq!(prev, top); + for i in 1..2000 { + let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}"); + prev = o; + } + if top == 0.9 { + let h = k[31][0] * 1e-5; + let after = (c.apply_rolloff(k[31][0] + h) - top) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + } + } + // a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2 + // extension) and still closes on white further up + for s in [0.0f32, 0.05] { + let mut k = knots(); + k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]); + let c = CameraTone::new(k).unwrap(); + let (x, top) = (k[31][0], k[31][1]); + let h = x * 1e-4; + let after = (c.apply_rolloff(x + h) - top) / h; + assert!((after - s).abs() < 0.01, "{s}: right slope {after}"); + let mut prev = top; + for i in 1..3000 { + let o = c.apply_rolloff(x * 1.005f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}"); + prev = o; + } + assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}"); + for y in [f32::MAX, f32::INFINITY] { + assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}"); + } + } + // hostile input + for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] { + let o = curve.apply_rolloff(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + // the tone map built from it is monotone and bounded, SDR and HDR + for peak in [1.0f32, 4.0] { + let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak); + let mut prev = -1.0; + for i in 0..2400 { + let o = t.apply(1e-5 * 1.01f32.powi(i)); + assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}"); + prev = o; + } + } + } + + #[test] + fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] { + for peak in [1.0f32, 4.0] { + let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak)); + let (clip, roll) = (clip.lut(), roll.lut()); + // the generic curve up to the knee, never brighter past it + let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table"); + assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}"); + for (i, (r, c)) in roll.iter().zip(clip).enumerate() { + assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}"); + } + // same value and slope at the join: the step across it is the step before it + let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]); + assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}"); + // monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR) + assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}"); + if peak == 1.0 { + assert_eq!(clip[LUT_N - 1], 1.0); + // close to it at the top of the table at default settings (10 EV over grey); + // Whites −100 moves the white point, and so the shoulder, up 1.6 stops + let top = roll[LUT_N - 1]; + assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}"); + } + } + } + // no kink where V1/V2 clip: there the clipped curve stops rising at once + let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0)); + let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max); + assert!(kink(clip.lut()) > 0.9); + assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut())); + // hostile input (NaN passes through `ToneMap::apply` as on every curve) + for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] { + let o = roll.apply(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + } + + #[test] + fn monotone_and_bounded() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] { + let t = ToneMap::new(c, w, b); + let mut prev = -1.0; + for i in 0..2000 { + let y = 1e-5 * 1.012f32.powi(i); + let o = t.apply(y); + assert!((0.0..=1.0).contains(&o)); + assert!(o >= prev - 1e-6, "{c} {w} {b} at {y}: {o} < {prev}"); + prev = o; + } + } + } + + #[test] + fn hdr_is_sdr_at_peak_one_and_reaches_peak() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] { + assert_eq!(ToneMap::hdr(c, w, b, 1.0).lut(), ToneMap::new(c, w, b).lut()); + for peak in [2.0f32, 8.0, 32.0] { + let sdr = ToneMap::new(c, w, b); + let t = ToneMap::hdr(c, w, b, peak); + let mut prev = -1.0; + for i in 0..2400 { + let y = 1e-5 * 1.01f32.powi(i); + let o = t.apply(y); + assert!((0.0..=peak).contains(&o), "{c} {w} {b} {peak} at {y}: {o}"); + assert!(o >= prev - 1e-6, "{c} {w} {b} {peak} at {y}: {o} < {prev}"); + prev = o; + if y <= GREY * 2f32.powf(0.9) { + assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}"); + } + } + assert!(t.apply(4.0) > sdr.apply(4.0)); + if (c, w, b) == (0.0, 0.0, 0.0) { + assert!(t.apply(GREY * 2f32.powf(LUT_MAX_EV)) > peak * 0.99, "{peak}"); + } + } + } + // a broken peak falls back to SDR + assert_eq!(ToneMap::hdr(0.0, 0.0, 0.0, f32::NAN).lut(), ToneMap::new(0.0, 0.0, 0.0).lut()); + } + + #[test] + fn camera_hdr_keeps_the_camera_look_and_lifts_highlights() { + let curve = CameraTone::new(knots()).unwrap().with_chroma([1.2, 1.1, 1.0, 1.0, 0.9, 0.8, 0.7, 0.6]).unwrap(); + for (c, w, b) in [(0.0, 0.0, 0.0), (40.0, -30.0, -20.0)] { + let sdr = ToneMap::camera(&curve, c, w, b); + assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, 1.0).lut(), sdr.lut()); + assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, f32::NAN).lut(), sdr.lut()); + for peak in [2.0f32, 8.0] { + let t = ToneMap::camera_hdr(&curve, c, w, b, peak); + assert_eq!(t.chroma_lut(), sdr.chroma_lut()); + let mut prev = -1.0; + for i in 0..2400 { + let y = 1e-5 * 1.01f32.powi(i); + let o = t.apply(y); + assert!((0.0..=peak).contains(&o), "{peak} at {y}: {o}"); + assert!(o >= prev - 1e-6, "{peak} at {y}: {o} < {prev}"); + prev = o; + // the camera's midtones, not the generic HDR curve's (issue: dark HDR exports) + if y <= GREY * 2f32.powf(HDR_FROM_EV - 0.01) { + assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}: {o} vs {}", sdr.apply(y)); + } + } + assert!(t.apply(4.0) > 1.0 && t.apply(4.0) > sdr.apply(4.0) + 0.5, "{peak}: highlights lifted"); + } + } + } + + #[test] + fn display_hdr_passes_hdr_sources_and_keeps_sdr() { + assert_eq!(ToneMap::display_hdr(20.0, 10.0, -5.0, 1.0).lut(), ToneMap::display(20.0, 10.0, -5.0).lut()); + let t = ToneMap::display_hdr(0.0, 0.0, 0.0, 8.0); + for i in 1..=90 { + let y = i as f32 / 100.0; + assert!((t.apply(y) - y).abs() < 2e-3, "{y} -> {}", t.apply(y)); + } + let mut prev = 0.0; + for i in 1..2000 { + let o = t.apply(i as f32 / 100.0); + assert!(o >= prev - 1e-6 && o <= 8.0); + prev = o; + } + assert!(t.apply(3.0) > 2.0 && t.apply(3.0) < 3.0); + } + + #[test] + fn display_identity_and_monotone() { + let t = ToneMap::display(0.0, 0.0, 0.0); + // up to and including white (issue #1945: 1.0 came out as 0.9875, 8-bit 255 as 254); the + // tolerance is the LUT's interpolation next to the clip at 1.0, far below an 8-bit level + for i in 1..=100 { + let y = i as f32 / 100.0; + assert!((t.apply(y) - y).abs() < 1e-3, "{y} -> {}", t.apply(y)); + } + assert_eq!(t.apply(4.0), 1.0, "neutral values pushed above white clip"); + for (c, w, b) in [(100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (60.0, -40.0, 30.0)] { + let t = ToneMap::display(c, w, b); + let mut prev = -1.0; + for i in 0..1000 { + let o = t.apply(i as f32 / 500.0); + assert!(o >= prev - 1e-5, "{c} {w} {b}"); + prev = o; + } + } + let c = ToneMap::display(60.0, 0.0, 0.0); + assert!(c.apply(0.05) < 0.05 && c.apply(0.7) > 0.7); + } + + #[test] + fn display_shoulder_stays_on_edited_curves() { + // The short shoulder is part of the V1 look of edited curves (docs/process-versions.md); + // only neutral settings are the identity. + for (c, w, b) in [(20.0, 0.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, -5.0)] { + let t = ToneMap::display(c, w, b); + let o = t.apply(1.0); + assert!(o < 0.999 && o > 0.95, "{c} {w} {b}: {o}"); + } + } + + #[test] + fn grey_stays_near_grey_and_highlights_roll_off() { + let t = ToneMap::new(0.0, 0.0, 0.0); + let g = t.apply(0.18); + assert!((0.15..0.24).contains(&g), "{g}"); + assert!(t.apply(1.0) < 0.95 && t.apply(1.0) > 0.6); + assert!(t.apply(8.0) > 0.97); + } + + #[test] + fn sliders_move_the_right_way() { + let base = ToneMap::new(0.0, 0.0, 0.0); + let contrast = ToneMap::new(60.0, 0.0, 0.0); + assert!(contrast.apply(0.05) < base.apply(0.05)); + assert!(contrast.apply(0.8) > base.apply(0.8)); + assert!(ToneMap::new(0.0, 60.0, 0.0).apply(0.8) > base.apply(0.8)); + assert!(ToneMap::new(0.0, 0.0, -60.0).apply(0.01) < base.apply(0.01)); + assert!(ToneMap::new(0.0, 0.0, 60.0).apply(0.01) > base.apply(0.01)); + } +} diff --git a/crates/dialogs/src/service.rs b/crates/dialogs/src/service.rs index a2204531a..e4e93f1ca 100644 --- a/crates/dialogs/src/service.rs +++ b/crates/dialogs/src/service.rs @@ -11,8 +11,8 @@ //! otherwise in the last folder chosen for the same purpose; a Save that names an existing file the //! OS panel did not ask about gets the Replace question (PhotoCraft `file_dialog.rs:193 //! replaces_unasked`), a native message box from [`FilePanels::pump`] or, with the `ui` feature, a -//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and an uppercase -//! extension is lowercased (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two +//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and a new file's +//! uppercase extension is lowercased, while an existing file keeps its spelling (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two //! steps are separate settings of the [`ExtensionPolicy`]. use std::collections::{HashMap, VecDeque}; @@ -114,7 +114,8 @@ fn same_entry(a: &Path, b: &Path) -> bool { /// PhotoCraft with Lowercase Extension off still adds the suggested extension. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ExtensionPolicy { - /// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`). + /// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`), unless the + /// typed name is a file that already exists. pub lowercase: bool, /// Add the request's suggested extension to a name that has none. pub add_suggested: bool, @@ -425,11 +426,18 @@ impl FilePanels { /// The saved path after the extension policy: `"Photo"` becomes `"Photo.png"` with a /// suggested `png` (when `add_suggested`); `"Photo.PNG"` becomes `"Photo.png"` (when - /// `lowercase`); a path with another known extension is kept. + /// `lowercase`) unless a file named `"Photo.PNG"` already exists; a path with another known + /// extension is kept. + /// + /// An existing file keeps the spelling the panel answered: the panel has just asked whether to + /// replace that entry, and `"PHOTO.png"` next to `"PHOTO.PNG"` on a file system that tells + /// letter case apart is a second file, so the one the user picked would be left unchanged. // pc: crates/ui-egui/src/file_dialog.rs:210 lowercased_extension, :365 saved_path pub fn settled_save_path(policy: ExtensionPolicy, answered: &Path, suggested: Option<&str>) -> PathBuf { match answered.extension().and_then(|e| e.to_str()) { - Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) => answered.with_extension(ext.to_ascii_lowercase()), + Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) && !answered.exists() => { + answered.with_extension(ext.to_ascii_lowercase()) + } Some(_) => answered.to_path_buf(), None => match suggested { Some(ext) if policy.add_suggested => answered.with_extension(ext), @@ -691,4 +699,22 @@ mod service_tests { assert_eq!(log.borrow().len(), 3, "no question for a path the panel asked about"); let _ = std::fs::remove_dir_all(&dir); } + + // Saving over an existing `PHOTO.PNG` with Lowercase Extension on writes `PHOTO.PNG`, the + // file the panel asked about, not a new `PHOTO.png` beside it (on a file system that tells + // letter case apart) or a renamed one (on one that does not). A new name is still lowercased. + #[trial] + fn an_existing_file_keeps_its_extension_spelling() { + let dir = std::env::temp_dir().join(format!("craft-dialogs-existing-case-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + std::fs::write(dir.join("PHOTO.PNG"), b"old").expect("existing file"); + let typed = |name: &str| Answer::Paths(vec![dir.join(name)]); + let (service, mut panels, log) = service_with(vec![typed("PHOTO.PNG"), typed("Other.PNG")]); + let lowercase = ExtensionPolicy::default(); + + assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("PHOTO.PNG")]), "the existing file is replaced"); + assert_eq!(log.borrow().len(), 1, "no second question: the panel asked about this file"); + assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("Other.png")]), "a new file is lowercased"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index f5554222b..801b3d2d8 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -71,14 +71,16 @@ pub enum BezierTool { Convert, /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). Anchors, - /// Add Anchor Point: a press on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` - /// ([`PathEdit::InsertAnchor`]); a drag moves the new anchor, which is selected. A press on an anchor or a shown - /// handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it - /// alone), and a click on empty canvas deselects the anchors and keeps the path. With ⌥ a click on a segment selects - /// its whole subpath and a drag moves a copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that - /// takes no copies), and a press on an anchor does nothing. Hover: the segment mark with the anchor a click adds - /// ([`HitMark`]) and the pen with "+"; over an anchor the arrow; with ⌥ no mark and the arrow with "+"; the - /// crosshair under the canvas's precise cursor ([`CanvasSpace::precise`]). + /// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` + /// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does + /// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is + /// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to + /// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the + /// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it + /// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does + /// nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor + /// the arrow; with ⌥ no mark and the arrow with "+"; the crosshair under the canvas's precise cursor + /// ([`CanvasSpace::precise`]). AddAnchor, /// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it /// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark. @@ -241,6 +243,17 @@ enum Target { t: f64, from: Point, }, + /// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of + /// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and + /// `in_ctrl` the in handle ⌥ left once it broke the pair. + Pull { + path: u64, + segment: KnotRef, + t: f64, + from: Point, + out: Point, + in_ctrl: Option, + }, /// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point. Duplicate { path: u64, @@ -595,6 +608,12 @@ impl<'a> BezierOverlay<'a> { match hit { // Add Anchor with ⌥ takes the whole subpath as Direct's ⌥ does (PhotoCraft #12709). BezierHit::Segment { .. } if self.tool.takes_subpath(mods) => self.target(hit, start, mods, paths), + // Add Anchor's drag pulls out the new anchor's handles (PhotoCraft #12707); Auto Add/Delete's, and Delete + // Anchor's with ⌥, moves it. + BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => { + let from = Self::segment_point(paths, path, segment, t); + Target::Pull { path, segment, t, from, out: from, in_ctrl: None } + } BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => { Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) } } @@ -719,11 +738,40 @@ impl<'a> BezierOverlay<'a> { PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from } } &Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from }, + &Target::Pull { path, segment, t, from, in_ctrl, .. } => { + let to = from + delta; + let out = if mods.shift { handle_45(from, to) } else { snapped(to) }; + PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + } &Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from }, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None, }) } + /// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag + /// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass. + fn edit_pulled( + view: &CanvasView, + snap: Option<&Snap>, + tool: BezierTool, + target: &mut Target, + origin: Pos2, + pointer: Pos2, + mods: Mods, + ) -> Option { + if let Target::Pull { from, out, in_ctrl, .. } = target + && mods.alt + && in_ctrl.is_none() + { + *in_ctrl = Some(*from - (*out - *from)); + } + let edit = Self::edit(view, snap, tool, target, origin, pointer, mods); + if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) { + *out = *pulled; + } + edit + } + /// Proposes `paths` with `edit` applied to the paths the press began on. fn propose(&mut self, cx: &mut Cx<'_, Self>, start: &[EditPath], edit: PathEdit) { let mut next = start.to_vec(); @@ -896,7 +944,9 @@ impl<'a> BezierOverlay<'a> { let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. }); if first && moves { held.began = true; - if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } = held.target { + if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } | Target::Pull { path, segment, .. } = + held.target + { self.report.select = Some(self.inserted(path, segment)); } cx.begin(); @@ -910,7 +960,7 @@ impl<'a> BezierOverlay<'a> { } } _ => { - if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) { + if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) { self.propose(cx, &held.start, edit); } } @@ -938,7 +988,8 @@ impl<'a> BezierOverlay<'a> { return; } if held.began { - if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) { + let mut target = held.target.clone(); + if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) { self.propose(cx, &held.start, edit); } // The copy is what was dragged: it ends up selected, not the source. @@ -955,7 +1006,7 @@ impl<'a> BezierOverlay<'a> { self.set(cx, &held.start, PathEdit::InsertCurvature { path, segment, t, by: Vec2::ZERO }); self.report.select = Some(self.inserted(path, segment)); } - Target::Insert { path, segment, t, .. } => { + Target::Insert { path, segment, t, .. } | Target::Pull { path, segment, t, .. } => { self.set(cx, &held.start, PathEdit::InsertAnchor { path, segment, t, by: Vec2::ZERO }); self.report.select = Some(self.inserted(path, segment)); } @@ -1127,6 +1178,27 @@ fn nudge_vector(view: &CanvasView, direction: egui::Vec2, distance: f64) -> Vec2 if length > 0.0 { doc / length * distance } else { Vec2::ZERO } } +/// ⇧ on a handle pulled out of the anchor at `anchor` to `to`, as the reference application turns it: the nearest of +/// the eight 45° directions, an axis keeping the drag's offset along it and a diagonal the shorter of the two offsets +/// on both axes. `to` itself for a zero or non-finite offset. +fn handle_45(anchor: Point, to: Point) -> Point { + let d = to - anchor; + if !d.x.is_finite() || !d.y.is_finite() || d == Vec2::ZERO { + return to; + } + let (ax, ay) = (d.x.abs(), d.y.abs()); + // tan 22.5°: nearer the axis than the diagonal. + let tan = std::f64::consts::FRAC_PI_8.tan(); + if ay <= ax * tan { + Point::new(to.x, anchor.y) + } else if ax <= ay * tan { + Point::new(anchor.x, to.y) + } else { + let shorter = ax.min(ay); + anchor + Vec2::new(shorter.copysign(d.x), shorter.copysign(d.y)) + } +} + fn contains(r: DocRect, p: Point) -> bool { (r.x0..=r.x1).contains(&p.x) && (r.y0..=r.y1).contains(&p.y) } @@ -1145,7 +1217,7 @@ pub struct BezierOutput { pub select: Option, /// Add an anchor to the segment leaving a knot of a path, at `t` (PhotoCraft's Add Anchor Point): Insert on a /// picked anchor (`t` 0.5). A click or drag of an anchor tool on a segment is the [`change`](Self::change) - /// [`PathEdit::InsertAnchor`] instead. + /// [`PathEdit::InsertAnchor`] instead ([`PathEdit::PullAnchor`] for Add Anchor's drag). pub insert: Option<(u64, KnotRef, f64)>, /// Delete or Backspace with anchors selected under a tool that deletes (Direct, Convert, Curvature, Add Anchor, /// Delete Anchor): remove these anchors of a path (Delete Anchor Point), `segments` true; a Delete Anchor click diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index aeff532df..bbcce53f5 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -348,6 +348,22 @@ pub enum PathEdit { /// The move of the new anchor, in document units. by: Vec2, }, + /// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its + /// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth + /// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. + #[non_exhaustive] + PullAnchor { + /// The path's host key. + path: u64, + /// The anchor the segment leaves. + segment: KnotRef, + /// Position along the segment, 0..=1. + t: f64, + /// The new anchor's out handle. + out: Point, + /// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`. + in_ctrl: Option, + }, /// The Curvature tool's double-click or Enter on an anchor: a smooth knot becomes a corner /// with retracted handles and a corner becomes smooth, then the subpath reflows. #[non_exhaustive] @@ -425,6 +441,12 @@ impl PathEdit { PathEdit::InsertAnchor { path, segment, t, by } } + /// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out` + /// and mirrored, or with the in handle at `in_ctrl`. + pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option) -> Self { + PathEdit::PullAnchor { path, segment, t, out, in_ctrl } + } + /// The Curvature tool's toggle of `knot` between smooth and corner. pub fn toggle_curvature(path: u64, knot: KnotRef) -> Self { PathEdit::ToggleCurvature { path, knot } @@ -445,6 +467,7 @@ impl PathEdit { | PathEdit::MoveCurvature { path, .. } | PathEdit::InsertCurvature { path, .. } | PathEdit::InsertAnchor { path, .. } + | PathEdit::PullAnchor { path, .. } | PathEdit::ToggleCurvature { path, .. } | PathEdit::DuplicateSubpath { path, .. } => path, } diff --git a/crates/draw/src/ui/pen/bezier/ops.rs b/crates/draw/src/ui/pen/bezier/ops.rs index 4bf2b4a7a..889e4f576 100644 --- a/crates/draw/src/ui/pen/bezier/ops.rs +++ b/crates/draw/src/ui/pen/bezier/ops.rs @@ -137,6 +137,9 @@ impl PathEdit { /// `by`, then the subpath reflowed. /// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no /// reflow and no smoothing, so a straight segment gets a corner knot. + /// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in + /// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when + /// a handle is not finite. /// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner /// becomes smooth, then the subpath reflows. /// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`; @@ -203,6 +206,18 @@ impl PathEdit { k.in_ctrl += *by; k.out_ctrl += *by; } + PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => { + let finite = |p: &Point| p.x.is_finite() && p.y.is_finite(); + if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) { + return false; + } + let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false }; + let Some(at) = sp.insert_at(segment.knot, *t) else { return false }; + let k = &mut sp.knots[at]; + k.out_ctrl = *out; + k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor)); + k.smooth = in_ctrl.is_none(); + } PathEdit::Convert { knot, out, .. } => { if !knot_ok(path, *knot) { return false; diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index beeb41ff6..b7fe52b2a 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -73,6 +73,30 @@ fn edit_subpath_insert_at_splits_a_curve_without_changing_it() { // MoveAnchors, MoveHandle (smooth and alone), BendSegment (straight and curved), Convert give PhotoCraft's kernel // results; a wrong key or index changes nothing and returns false. +#[trial] +fn path_edit_pull_anchor_inserts_and_pulls_out_the_handles() { + let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false)); + let mut path = straight(); + assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), None).apply(&mut path)); + let k = path.subpaths[0].knots[1]; + assert!(near(k.anchor, p(50.0, 0.0)) && near(k.out_ctrl, p(50.0, 30.0)) && near(k.in_ctrl, p(50.0, -30.0)) && k.smooth, "{k:?}"); + let mut path = straight(); + assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), Some(p(80.0, 0.0))).apply(&mut path)); + let k = path.subpaths[0].knots[1]; + assert!(near(k.in_ctrl, p(80.0, 0.0)) && !k.smooth, "{k:?}"); + for bad in [ + PathEdit::pull_anchor(7, kr(0), 0.5, p(f64::NAN, 0.0), None), + PathEdit::pull_anchor(7, kr(0), 0.5, p(1.0, 1.0), Some(p(0.0, f64::INFINITY))), + PathEdit::pull_anchor(7, kr(0), 1.5, p(1.0, 1.0), None), + PathEdit::pull_anchor(7, kr(4), 0.5, p(1.0, 1.0), None), + PathEdit::pull_anchor(7, KnotRef::new(3, 0), 0.5, p(1.0, 1.0), None), + ] { + let mut path = straight(); + assert!(!bad.apply(&mut path), "{bad:?}"); + assert_eq!(path, straight()); + } +} + #[trial] fn path_edit_apply_matches_the_kernel_for_every_existing_edit() { let base = || { @@ -417,12 +441,13 @@ fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_n assert_eq!(h.state.borrow().selection, picked, "the page key picks no part"); } -// Add Anchor on a segment: a press, a drag and a release are one gesture that inserts the anchor and moves it, with the -// new anchor selected; a click inserts it where the segment was pressed and moves nothing. +// The Pen's Auto Add/Delete on a segment: a press, a drag and a release are one gesture that inserts the anchor and +// moves it, with the new anchor selected. Add Anchor's click inserts it where the segment was pressed and moves +// nothing (its drag pulls out handles: `an_add_anchor_drag_pulls_out_the_new_anchors_handles`). #[trial] fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() { let mut h = two_paths(); - h.update(|st| st.tool = BezierTool::AddAnchor); + h.update(|st| st.tool = BezierTool::AutoAddDelete); let on = h.screen(p(110.0, 60.0)); h.drag(on, vec2(0.0, FAR)); { @@ -453,6 +478,73 @@ fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() { assert_eq!(st.selection, sel(1, &[(0, 1)])); } +// Add Anchor's drag from a segment inserts the anchor where the segment was pressed and pulls out its handles, as the +// reference application does (PhotoCraft #12707): the out handle follows the pointer and the in handle mirrors it, in +// one gesture, the new anchor selected and smooth; ⇧ turns the handle to the nearest 45°, an axis keeping the +// drag's offset along it and a diagonal the shorter offset; ⌥ pressed during the drag breaks the pair, so only the +// out handle follows from then on. +#[trial] +fn an_add_anchor_drag_pulls_out_the_new_anchors_handles() { + let add_anchor = || { + let mut h = two_paths(); + h.update(|st| st.tool = BezierTool::AddAnchor); + h + }; + let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6; + let on = p(110.0, 60.0); + + let mut h = add_anchor(); + let at = h.screen(on); + h.drag(at, vec2(0.0, 60.0)); + { + let st = h.state.borrow(); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen); + assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)), "{:?}", st.seen); + assert!( + matches!(st.changes.last(), Some(PathEdit::PullAnchor { path: 1, segment, in_ctrl: None, .. }) if *segment == kr(0)), + "{:?}", + st.changes + ); + let knots = &st.paths[0].subpaths[0].knots; + assert_eq!(knots.len(), 5); + let k = knots[1]; + assert!(k.anchor.distance(on) < 1e-3, "the anchor stays where the segment was pressed: {k:?}"); + assert!(close(k.out_ctrl - k.anchor, Vec2::new(0.0, 60.0)) && close(k.in_ctrl - k.anchor, Vec2::new(0.0, -60.0)), "{k:?}"); + assert!(k.smooth); + assert_eq!(st.selection, sel(1, &[(0, 1)])); + } + + // ⇧: the measured drags. + for (by, out) in [((30.0, 80.0), (0.0, 80.0)), ((70.0, 40.0), (40.0, 40.0)), ((-50.0, -60.0), (-50.0, -50.0)), ((60.0, -20.0), (60.0, 0.0))] { + let mut h = add_anchor(); + let at = h.screen(on); + h.fixture.hold(egui::Modifiers::SHIFT); + h.drag(at, vec2(by.0, by.1)); + h.fixture.hold(egui::Modifiers::NONE); + let st = h.state.borrow(); + let k = st.paths[0].subpaths[0].knots[1]; + let out = Vec2::new(out.0, out.1); + assert!(close(k.out_ctrl - k.anchor, out) && close(k.in_ctrl - k.anchor, -out), "{by:?}: {k:?}"); + } + + // ⌥ during the drag: the in handle stays where the pair had it, the out handle follows on. + let mut h = add_anchor(); + let at = h.screen(on); + h.press_at(at); + h.move_to(at + vec2(-30.0, 0.0)); + h.move_to(at + vec2(-60.0, 0.0)); + h.fixture.hold(egui::Modifiers::ALT); + h.move_to(at + vec2(-60.0, 20.0)); + h.move_to(at + vec2(-60.0, 40.0)); + h.release_at(at + vec2(-60.0, 40.0)); + h.fixture.hold(egui::Modifiers::NONE); + let st = h.state.borrow(); + let k = st.paths[0].subpaths[0].knots[1]; + assert!(close(k.out_ctrl - k.anchor, Vec2::new(-60.0, 40.0)) && close(k.in_ctrl - k.anchor, Vec2::new(60.0, 0.0)), "{k:?}"); + assert!(!k.smooth, "a broken pair is a corner"); + assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen); +} + // Convert on a segment: a drag on a straight one bends it when nothing of the path is selected and moves the path when // every anchor is, a partial selection and a curved segment do nothing; handles within the straightness tolerance of // their anchors still make the segment straight. diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 9475d2054..5fcbfc9d4 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -344,6 +344,26 @@ impl ErrorBars { } } +/// A chart's data table (`c:dTable`), independent of the chart legend. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ChartDataTable { + pub show_keys: bool, + pub horizontal_border: bool, + pub vertical_border: bool, + pub outline: bool, +} + +impl Default for ChartDataTable { + fn default() -> Self { + Self { show_keys: true, horizontal_border: true, vertical_border: true, outline: true } + } +} + +fn is_zero_u16(v: &u16) -> bool { + *v == 0 +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Chart { @@ -423,6 +443,15 @@ pub struct Chart { /// A histogram's bin width (`cx:binSize`). #[serde(skip_serializing_if = "Option::is_none")] pub bin_size: Option, + /// A chart's data table (`c:dTable`). + #[serde(skip_serializing_if = "Option::is_none")] + pub data_table: Option, + /// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359). + #[serde(skip_serializing_if = "is_zero_u16")] + pub first_slice_angle: u16, + /// A PivotChart's PivotTable reference (`c:pivotSource/c:name`). + #[serde(skip_serializing_if = "Option::is_none")] + pub pivot_source: Option, /// Original chart XML part kept for round-trip of unmodelled options. #[serde(skip_serializing_if = "Option::is_none")] pub raw: Option, @@ -537,6 +566,9 @@ impl Default for Chart { up_down_bars: false, bin_count: None, bin_size: None, + data_table: None, + first_slice_angle: 0, + pivot_source: None, raw: None, verbatim: false, kept: ChartKept::default(), diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 3f2be736f..735ceb8c8 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -1,6 +1,6 @@ //! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`. -use crate::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType}; +use crate::chart::{Chart, ChartDataTable, ChartType, ErrorBars, Series, Trendline, TrendlineType}; use crate::style::Fill; use craft_xml::{El, Local, value}; @@ -194,6 +194,16 @@ fn chart_within(root: &El, mut budget: usize) -> Option { } } c.lang = root.child(Local("lang")).and_then(|c| c.attr_local("val")).map(str::to_string); + c.pivot_source = root.path(&[Local("pivotSource"), Local("name")]).map(|n| n.deep_text().trim().to_string()).filter(|n| !n.is_empty()); + c.data_table = pa.child(Local("dTable")).map(|t| { + let flag = |name: &str| t.child(Local(name)).is_some_and(|e| e.attr_local("val").and_then(value::to_bool).unwrap_or(true)); + ChartDataTable { + show_keys: flag("showKeys"), + horizontal_border: flag("showHorzBorder"), + vertical_border: flag("showVertBorder"), + outline: flag("showOutline"), + } + }); let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val); read_text_styles(&mut c, root, ch, val_ax, cat_ax); Some(c) @@ -288,6 +298,9 @@ fn read_group_settings(g: &El, c: &mut Chart) -> Option { if let Some(v) = g.child(Local("holeSize")).and_then(|c| c.attr_local("val")).and_then(|v| v.parse::().ok()) { c.hole_size = (v / 100.0).clamp(0.0, 0.9); } + if let Some(v) = g.child(Local("firstSliceAng")).and_then(|c| c.attr_local("val")).and_then(|v| v.trim().parse::().ok()) { + c.first_slice_angle = v % 360; + } // `` without a val attribute means true, as in the schema's default. // The setting belongs to this plot group: a group that asks for no labels keeps them // off, even when another group of a combo chart asks for them (#868). @@ -902,4 +915,30 @@ mod tests { assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| !c.vary_colors)); assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| c.vary_colors)); } + + #[test] + fn data_table_first_slice_angle_and_pivot_source_roundtrip() { + let xml = format!( + r#"[Book.xlsx]Sheet1!PivotTable15"# + ); + let c = read_chart_xml(xml.as_bytes()).unwrap(); + assert_eq!(c.pivot_source.as_deref(), Some("[Book.xlsx]Sheet1!PivotTable1")); + assert_eq!(c.data_table, Some(ChartDataTable { show_keys: true, horizontal_border: true, vertical_border: false, outline: true })); + let mut edited = c.clone(); + edited.raw = None; + let (written, kept) = crate::chart::write::chart_xml(&edited); + assert!(!kept); + let back = read_chart_xml(&written).unwrap(); + assert_eq!(back.pivot_source, c.pivot_source); + assert_eq!(back.data_table, c.data_table); + + let pie_xml = format!( + r#"5"# + ); + let mut pie = read_chart_xml(pie_xml.as_bytes()).unwrap(); + assert_eq!(pie.first_slice_angle, 90); + pie.raw = None; + let (pie_written, _) = crate::chart::write::chart_xml(&pie); + assert_eq!(read_chart_xml(&pie_written).unwrap().first_slice_angle, 90); + } } diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index ca1f61acd..9dbef30d2 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -645,9 +645,9 @@ fn plot_group(w: &mut Writer, c: &Chart, kind: ChartType, list: &[(usize, &Serie w.close(); } } - Group::Pie => w.tag("c:firstSliceAng").attr("val", 0).empty(), + Group::Pie => w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(), Group::Doughnut => { - w.tag("c:firstSliceAng").attr("val", 0).empty(); + w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(); w.tag("c:holeSize").attr("val", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64).empty(); } _ => {} @@ -733,6 +733,12 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { w.tag("c:date1904").attr("val", 0).empty(); w.tag("c:roundedCorners").attr("val", 0).empty(); w.tag("c:style").attr("val", c.style.clamp(1, 48)).empty(); + if let Some(pivot) = c.pivot_source.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + w.open("c:pivotSource", &[]); + w.tag("c:name").text(pivot); + w.tag("c:fmtId").attr("val", 0).empty(); + w.close(); + } w.open("c:chart", &[]); match &c.title { Some(t) => { @@ -802,6 +808,22 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { axes(&mut w, c, g); } } + if let Some(dt) = &c.data_table { + w.open("c:dTable", &[]); + if dt.horizontal_border { + w.empty("c:showHorzBorder", &[]); + } + if dt.vertical_border { + w.empty("c:showVertBorder", &[]); + } + if dt.outline { + w.empty("c:showOutline", &[]); + } + if dt.show_keys { + w.empty("c:showKeys", &[]); + } + w.close(); + } if let Some(f) = &c.plot_fill { sp_pr(&mut w, Some(f), None); } diff --git a/crates/drawingml/src/table.rs b/crates/drawingml/src/table.rs index e5fbe1f97..b5d83d530 100644 --- a/crates/drawingml/src/table.rs +++ b/crates/drawingml/src/table.rs @@ -83,6 +83,12 @@ impl Default for Table { } } +/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75). +pub const MAX_CELLS: usize = 100_000; +/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few +/// passes over the largest grid, where a real table needs one or two. +const MAX_MERGE_WORK: usize = 16 * MAX_CELLS; + impl Table { pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self { let rows = rows.clamp(1, 1000); @@ -113,15 +119,26 @@ impl Table { self.rows.iter().map(|r| r.height).sum() } /// Insert an empty row before `at`. A merge the new row falls inside grows to cover it. - pub fn insert_row(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`]. + #[must_use] + pub fn insert_row(&mut self, at: usize) -> bool { + if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS { + return false; + } let at = at.min(self.rows.len()); let merges = self.merges(); let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0); self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() }); self.set_merges(merges.into_iter().map(|m| m.insert_row(at))); + true } /// Insert an empty column before `at`. A merge the new column falls inside grows to cover it. - pub fn insert_col(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`]. + #[must_use] + pub fn insert_col(&mut self, at: usize) -> bool { + if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS { + return false; + } let at = at.min(self.cols.len()); let merges = self.merges(); let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0); @@ -131,6 +148,7 @@ impl Table { r.cells.insert(i, Cell::new("")); } self.set_merges(merges.into_iter().map(|m| m.insert_col(at))); + true } /// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and /// text) to the next row it covers. @@ -170,8 +188,12 @@ impl Table { true } /// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid. + /// Merges of a well-formed table do not overlap, so together they cover at most the grid; a + /// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells + /// without bound. fn merges(&self) -> Vec { let (nr, nc) = (self.rows.len(), self.cols.len()); + let mut area = nr.saturating_mul(nc); let mut out = vec![]; for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(nc) { @@ -180,7 +202,10 @@ impl Table { } let rs = (cell.row_span.max(1) as usize).min(nr - r); let gs = (cell.grid_span.max(1) as usize).min(nc - c); - if rs > 1 || gs > 1 { + if (rs > 1 || gs > 1) + && let Some(left) = area.checked_sub(rs.saturating_mul(gs)) + { + area = left; out.push(Merge { r, c, rs, gs }); } } @@ -233,9 +258,17 @@ impl Table { if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) { return false; } - // Grow the rectangle until no existing merge sticks out of it. + // Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole + // grid and may grow it by one row, so the passes are charged against + // [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed. let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1); + let pass = self.rows.len().saturating_mul(self.cols.len()).max(1); + let mut work = 0usize; loop { + work = work.saturating_add(pass); + if work > MAX_MERGE_WORK { + return false; + } let before = (r0, c0, r1, c1); for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) { @@ -289,21 +322,50 @@ impl Table { return false; } // Spans come from the file and may reach past the table; only walk the cells that exist. - for rr in r..r.saturating_add(rs).min(self.rows.len()) { - for cc in c..c.saturating_add(gs).min(self.cols.len()) { - if let Some(x) = self.cell_mut(rr, cc) { - x.h_merge = false; - x.v_merge = false; - x.grid_span = 1; - x.row_span = 1; - } + let end = r.saturating_add(rs).min(self.rows.len()); + let gs = gs.min(self.cols.len().saturating_sub(c)); + for row in self.rows.get_mut(r..end).unwrap_or_default() { + for x in row.cells.iter_mut().skip(c).take(gs) { + x.h_merge = false; + x.v_merge = false; + x.grid_span = 1; + x.row_span = 1; } } true } - /// Make every row have exactly `cols.len()` cells (repair after loading). - pub fn normalize(&mut self) { + /// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row + /// exactly `cols.len()` cells wide. + pub fn is_normalized(&self) -> bool { let n = self.cols.len(); + n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n) + } + /// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`]. + pub fn over_cap(&self) -> bool { + let n = self.cols.len(); + n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1) + } + /// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that + /// survive (an oversized table is not copied whole first). + pub fn normalized(&self) -> Table { + let n = self.cols.len().min(MAX_CELLS); + let keep = (MAX_CELLS / n.max(1)).max(1); + let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect(); + let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self }; + t.normalize(); + if self.over_cap() { + t.clip_spans(); + } + t + } + /// Make every row have exactly `cols.len()` cells (repair after loading). A grid over + /// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many + /// columns but few cells cannot make this allocate their product. + pub fn normalize(&mut self) { + let truncated = self.over_cap(); + self.cols.truncate(MAX_CELLS); + let n = self.cols.len(); + self.rows.truncate((MAX_CELLS / n.max(1)).max(1)); for r in &mut self.rows { r.cells.resize_with(n, || Cell::new("")); for c in &mut r.cells { @@ -311,6 +373,20 @@ impl Table { c.row_span = c.row_span.max(1); } } + if truncated { + self.clip_spans(); + } + } + /// Cut every merge span to the rows and columns that remain, so no merge reaches past a + /// table that lost rows or columns to the cell cap. + fn clip_spans(&mut self) { + let (nr, nc) = (self.rows.len(), self.cols.len()); + for (ri, r) in self.rows.iter_mut().enumerate() { + for (ci, c) in r.cells.iter_mut().enumerate() { + c.row_span = c.row_span.min((nr - ri) as u32).max(1); + c.grid_span = c.grid_span.min((nc - ci) as u32).max(1); + } + } } } @@ -554,10 +630,10 @@ mod tests { fn row_and_column_edits_keep_merges_consistent() { for at in 0..=4 { let mut t = merged(); - t.insert_row(at); + assert!(t.insert_row(at)); assert_topology(&t); let mut t = merged(); - t.insert_col(at); + assert!(t.insert_col(at)); assert_topology(&t); } for at in 0..4 { @@ -573,11 +649,11 @@ mod tests { #[test] fn inserting_inside_a_merge_grows_it() { let mut t = merged(); - t.insert_row(2); + assert!(t.insert_row(2)); let a = t.cell(1, 1).unwrap(); assert_eq!((a.row_span, a.grid_span), (3, 2)); assert!(t.cell(2, 2).unwrap().h_merge && t.cell(2, 2).unwrap().v_merge); - t.insert_col(0); + assert!(t.insert_col(0)); assert_eq!(t.cell(1, 2).unwrap().grid_span, 2); assert_eq!(anchor_text(&t, 1, 2), "M"); assert_topology(&t); @@ -619,8 +695,8 @@ mod tests { fn insert_delete_merge_split() { let mut t = Table::new(3, 3, 300.0, 30.0); assert_eq!((t.n_rows(), t.n_cols()), (3, 3)); - t.insert_row(1); - t.insert_col(3); + assert!(t.insert_row(1)); + assert!(t.insert_col(3)); assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); assert!(t.delete_row(0) && t.delete_col(0)); assert_eq!((t.n_rows(), t.n_cols()), (3, 3)); @@ -646,6 +722,89 @@ mod tests { assert!(t.split(0, 0)); assert_eq!(t.cell(0, 0).map(|c| (c.grid_span, c.row_span)), Some((1, 1))); } + + #[test] + fn merge_refuses_work_past_cap() { + let mut t = Table::new(1000, 10, 100.0, 10.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.row_span = 2; + } + } + let before = t.clone(); + assert!(!t.merge(998, 0, 999, 9)); + assert_eq!(t, before); + let mut small = Table::new(4, 4, 400.0, 30.0); + assert!(small.merge(0, 0, 1, 1)); + assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized()); + } + + #[test] + fn normalize_caps_a_sparse_grid_at_max_cells() { + let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() }; + t.normalize(); + assert_eq!(t.cols.len(), 1000); + assert_eq!(t.rows.len(), MAX_CELLS / 1000); + assert!(t.rows.iter().all(|r| r.cells.len() == 1000)); + let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() }; + t.normalize(); + assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1)); + let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() }; + let mut n = wide.clone(); + n.normalize(); + assert_eq!(wide.normalized(), n); + let mut t = Table::new(4, 4, 400.0, 30.0); + t.normalize(); + assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); + } + + #[test] + fn overlapping_file_spans_rebuild_in_bounded_work() { + let n = 200; + let mut t = Table::new(n, n, 400.0, 30.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.grid_span = u32::MAX; + c.row_span = u32::MAX; + } + } + assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid"); + assert!(t.insert_row(n)); + assert_eq!(t.n_rows(), n + 1); + assert!(t.split(0, 0)); + } + + #[test] + fn insert_past_the_cap_is_refused() { + const { assert!(MAX_CELLS >= 75 * 75) }; + let mut t = + Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() }; + assert!(!t.over_cap()); + let before = t.clone(); + assert!(!t.insert_row(0)); + assert!(!t.insert_col(0)); + assert_eq!(t, before); + assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0)); + } + + #[test] + fn merges_are_clipped_when_the_cap_drops_rows() { + let cols = 1000; + let rows = MAX_CELLS / cols + 1; + let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() }; + t.rows[0].cells[0].row_span = rows as u32; + t.rows[0].cells[cols - 1].grid_span = 5; + let n = t.normalized(); + assert_eq!(n.rows.len(), rows - 1); + assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1); + assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1); + t.normalize(); + assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1); + let mut small = Table::new(3, 3, 30.0, 10.0); + small.rows[2].cells[2].grid_span = 4; + small.normalize(); + assert_eq!(small.rows[2].cells[2].grid_span, 4); + } } pub mod styles; diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index cdd725a7d..5dd52af53 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -12,6 +12,7 @@ use std::io::Write as _; pub mod drawing; +pub mod lin_pat; pub mod model; pub mod mtext; pub mod mtext_tokens; diff --git a/crates/dxf/src/lin_pat.rs b/crates/dxf/src/lin_pat.rs new file mode 100644 index 000000000..309f0567a --- /dev/null +++ b/crates/dxf/src/lin_pat.rs @@ -0,0 +1,391 @@ +//! Readers for AutoCAD-compatible linetype (`.lin`) and hatch pattern (`.pat`) text files. +//! +//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then +//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for +//! a pattern), with `;` starting a comment. Everything here treats the text as hostile: lines, +//! definitions, dashes, families and warnings are capped, numbers must be finite and reasonable, +//! and nothing panics. Problems become warnings and the definitions that can be read are kept. + +/// Longest line read; longer lines are skipped with a warning. +pub const MAX_LINE_CHARS: usize = 4096; +/// Most definitions (linetypes or patterns) read from one file. +pub const MAX_DEFINITIONS: usize = 4096; +/// Most elements in one linetype. +pub const MAX_LINETYPE_ELEMENTS: usize = 256; +/// Most line families in one hatch pattern. +pub const MAX_PATTERN_FAMILIES: usize = 1024; +/// Most dashes in one pattern line family. +pub const MAX_PATTERN_DASHES: usize = 256; +/// Largest magnitude accepted for a length, offset or scale. +pub const MAX_VALUE: f64 = 1.0e6; +/// Longest name or description kept. +const MAX_NAME_CHARS: usize = 255; +/// Most warnings collected; the rest are counted in a last line. +const MAX_WARNINGS: usize = 100; + +/// One element of a linetype parsed from a `.lin` file. +#[derive(Clone, Debug, PartialEq)] +pub struct LinDashElement { + /// Dash (`> 0`), gap (`< 0`), or dot (`0`) length in drawing units. + pub length: f64, + /// Embedded text string, if any. + pub text: Option, + /// Text style name for embedded text, if any. + pub style: Option, + /// Text scale factor (`S=`, default `1.0`). + pub scale: f64, + /// Text rotation in radians (`R=`, `A=`, or `U=`, default `0.0`). + pub rotation: f64, + /// Text X/Y offset (`X=`, `Y=`, default `[0.0, 0.0]`). + pub offset: [f64; 2], + /// Whether rotation is absolute (`A=`) rather than relative to the line (`R=` or `U=`). + pub absolute: bool, +} + +impl LinDashElement { + /// A simple dash, gap, or dot element with no embedded text. + #[must_use] + pub fn dash(length: f64) -> Self { + Self { length, text: None, style: None, scale: 1.0, rotation: 0.0, offset: [0.0, 0.0], absolute: false } + } +} + +/// A linetype definition parsed from a `.lin` file. +#[derive(Clone, Debug, PartialEq)] +pub struct LinDefinition { + pub name: String, + pub description: String, + pub pattern: Vec, +} + +/// One line family of a hatch pattern parsed from a `.pat` file. +/// +/// Values are in pattern-definition coordinates as written: `angle` in degrees, `origin` as +/// `[x, y]`, `delta` as `[delta_x, delta_y]` along/perpendicular to the line direction, and +/// `dashes` as dash (`> 0`), gap (`< 0`), and dot (`0`) lengths. +#[derive(Clone, Debug, PartialEq)] +pub struct PatLineFamily { + pub angle: f64, + pub origin: [f64; 2], + pub delta: [f64; 2], + pub dashes: Vec, +} + +/// A hatch pattern definition parsed from a `.pat` file. +#[derive(Clone, Debug, PartialEq)] +pub struct PatDefinition { + pub name: String, + pub description: String, + pub lines: Vec, +} + +/// What a file held: the definitions that could be read, and why anything else was skipped. +#[derive(Clone, Debug, PartialEq)] +pub struct Parsed { + pub items: Vec, + pub warnings: Vec, +} + +impl Default for Parsed { + fn default() -> Self { + Self { items: Vec::new(), warnings: Vec::new() } + } +} + +impl Parsed { + fn warn(&mut self, line: usize, msg: impl Into) { + match self.warnings.len() { + n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())), + MAX_WARNINGS => self.warnings.push("more problems not listed".into()), + _ => {} + } + } +} + +/// A header line `*NAME[,description]`: the name and description, or why it can't be used. +fn header(rest: &str) -> std::result::Result<(String, String), String> { + let (name, desc) = rest.split_once(',').unwrap_or((rest, "")); + let name = name.trim(); + if name.is_empty() { + return Err("a definition without a name".into()); + } + if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) { + return Err("a definition name that is too long or has control characters".into()); + } + let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect(); + Ok((name.to_string(), desc)) +} + +/// A finite number within ±[`MAX_VALUE`]. +fn number(t: &str) -> Option { + t.trim().parse::().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE) +} + +/// The file's text lines with 1-based numbers, without a leading byte-order mark. +fn lines(text: &str) -> impl Iterator { + text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim())) +} + +// ---------- LIN ---------- + +/// Read the linetypes of a `.lin` file. +/// +/// Simple linetypes and complex ones with embedded text +/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`) +/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept. +/// Lengths are in drawing units as written: a user's file is never rescaled. +#[must_use] +pub fn parse_lin(text: &str) -> Parsed { + let mut out = Parsed::default(); + // The definition being read: name, description, header line. + let mut pending: Option<(String, String, usize)> = None; + for (no, line) in lines(text) { + if line.is_empty() || line.starts_with(';') { + continue; + } + if line.chars().count() > MAX_LINE_CHARS { + out.warn(no, "line too long; skipped"); + continue; + } + if let Some(rest) = line.strip_prefix('*') { + if let Some((name, _, at)) = pending.take() { + out.warn(at, format!("linetype {name} has no pattern line; skipped")); + } + match header(rest) { + Ok((name, desc)) => pending = Some((name, desc, no)), + Err(e) => out.warn(no, format!("{e}; skipped")), + } + continue; + } + let Some((name, description, _)) = pending.take() else { + out.warn(no, "pattern line without a *NAME line before it; skipped"); + continue; + }; + if out.items.len() >= MAX_DEFINITIONS { + out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped")); + break; + } + if out.items.iter().any(|l: &LinDefinition| l.name.eq_ignore_ascii_case(&name)) { + out.warn(no, format!("linetype {name} is defined twice; the first definition is kept")); + continue; + } + match lin_pattern(line, no, &name, &mut out) { + Ok(pattern) => out.items.push(LinDefinition { name, description, pattern }), + Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")), + } + } + if let Some((name, _, at)) = pending { + out.warn(at, format!("linetype {name} has no pattern line; skipped")); + } + out +} + +/// Split a pattern line at commas outside `[…]` and `"…"`. +fn lin_fields(line: &str) -> std::result::Result, String> { + let mut out = Vec::new(); + let (mut depth, mut quoted, mut start) = (0usize, false, 0usize); + for (i, c) in line.char_indices() { + match c { + '"' => quoted = !quoted, + '[' if !quoted => depth = depth.saturating_add(1), + ']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?, + ',' if !quoted && depth == 0 => { + out.push(line.get(start..i).unwrap_or("").trim()); + start = i.saturating_add(1); + } + _ => {} + } + if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) { + return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements")); + } + } + if quoted || depth != 0 { + return Err("an unclosed [ or \"".into()); + } + out.push(line.get(start..).unwrap_or("").trim()); + Ok(out) +} + +/// The elements of a pattern line `A,dash,gap,[…],…`. +fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed) -> std::result::Result, String> { + let mut fields = lin_fields(line)?; + // The alignment field ("A") comes first; a line of plain numbers is read as well. + if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) { + fields.remove(0); + } else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) { + return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or(""))); + } + let mut pattern: Vec = Vec::new(); + for f in fields.into_iter().filter(|f| !f.is_empty()) { + if pattern.len() >= MAX_LINETYPE_ELEMENTS { + return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements")); + } + let Some(inner) = f.strip_prefix('[') else { + let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?; + pattern.push(LinDashElement::dash(len)); + continue; + }; + let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?; + match lin_text(inner)? { + Some(text) => { + // The text sits at the end of the element before it (a zero-length one if none). + if pattern.last().is_none_or(|e| e.text.is_some()) { + pattern.push(LinDashElement::dash(0.0)); + } + if let Some(last) = pattern.last_mut() { + *last = LinDashElement { length: last.length, ..text }; + } + } + None => { + let shape = inner.split(',').next().unwrap_or("").trim(); + out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which is not supported here; left out")); + } + } + } + if pattern.is_empty() { + return Err("no dashes".into()); + } + if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) { + return Err("every element has zero length".into()); + } + Ok(pattern) +} + +/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element. +fn lin_text(inner: &str) -> std::result::Result, String> { + let inner = inner.trim(); + let Some(after) = inner.strip_prefix('"') else { return Ok(None) }; + let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?; + if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) { + return Err("embedded text that is too long or has control characters".into()); + } + let mut parts = rest.split(',').map(str::trim); + if !parts.next().unwrap_or("").is_empty() { + return Err("text element: expected a comma after the text".into()); + } + let style = parts.next().unwrap_or("").trim(); + if style.is_empty() || style.contains('=') { + return Err("text element: the text style is missing".into()); + } + let mut e = LinDashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..LinDashElement::dash(0.0) }; + for kv in parts.filter(|p| !p.is_empty()) { + let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?; + match k.trim().to_ascii_uppercase().as_str() { + "S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?, + "X" => e.offset[0] = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?, + "Y" => e.offset[1] = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?, + // Upright text keeps a rotation relative to the line, like R. + k @ ("R" | "A" | "U") => { + e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?; + e.absolute = k == "A"; + } + other => return Err(format!("text element: unknown option `{other}`")), + } + } + Ok(Some(e)) +} + +/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out. +fn angle(t: &str) -> Option { + let t = t.trim().to_ascii_lowercase(); + let (num, unit) = match t.char_indices().last() { + Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c), + _ => (t.as_str(), 'd'), + }; + let v = num.trim().parse::().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?; + Some(match unit { + 'r' => v, + 'g' => v * std::f64::consts::PI / 200.0, + _ => v.to_radians(), + }) +} + +// ---------- PAT ---------- + +/// Read the hatch patterns of a `.pat` file. +/// +/// Values are used as written (an inch file for inch drawings, a millimetre file for metric ones). +#[must_use] +pub fn parse_pat(text: &str) -> Parsed { + let mut out: Parsed = Parsed::default(); + // The pattern being read, its header line, and whether it already failed. + let mut cur: Option<(PatDefinition, usize, bool)> = None; + for (no, line) in lines(text) { + // A comment runs to the end of the line. + let line = line.split(';').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + if line.chars().count() > MAX_LINE_CHARS { + out.warn(no, "line too long; skipped"); + continue; + } + if let Some(rest) = line.strip_prefix('*') { + finish_pat(cur.take(), &mut out); + match header(rest) { + Ok((name, description)) => cur = Some((PatDefinition { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)), + Err(e) => out.warn(no, format!("{e}; skipped")), + } + continue; + } + let Some((p, _, failed)) = cur.as_mut() else { + out.warn(no, "line family without a *NAME line before it; skipped"); + continue; + }; + if *failed { + continue; + } + if p.lines.len() >= MAX_PATTERN_FAMILIES { + out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name)); + *failed = true; + continue; + } + match pat_family(line) { + Ok(l) => p.lines.push(l), + Err(e) => { + out.warn(no, format!("pattern {}: {e}; skipped", p.name)); + *failed = true; + } + } + } + finish_pat(cur, &mut out); + out +} + +fn finish_pat(cur: Option<(PatDefinition, usize, bool)>, out: &mut Parsed) { + let Some((p, at, failed)) = cur else { return }; + if failed { + return; + } + if p.lines.is_empty() { + out.warn(at, format!("pattern {} has no line families; skipped", p.name)); + } else if out.items.len() >= MAX_DEFINITIONS { + out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name)); + } else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) { + out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name)); + } else { + out.items.push(p); + } +} + +/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`. +fn pat_family(line: &str) -> std::result::Result { + let mut v = Vec::new(); + for f in line.split(',') { + if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) { + return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family")); + } + let f = f.trim(); + if f.is_empty() && v.len() >= 5 { + continue; + } + v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?); + } + let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else { + return Err("a line family needs angle, x, y, delta-x and delta-y".into()); + }; + if dy.abs() < 1e-9 { + return Err("a line family with zero spacing (delta-y)".into()); + } + Ok(PatLineFamily { angle, origin: [x, y], delta: [dx, dy], dashes: v.get(5..).unwrap_or(&[]).to_vec() }) +} diff --git a/crates/dxf/tests/lin_pat.rs b/crates/dxf/tests/lin_pat.rs new file mode 100644 index 000000000..afe45d056 --- /dev/null +++ b/crates/dxf/tests/lin_pat.rs @@ -0,0 +1,180 @@ +//! Tests for `.lin` and `.pat` text resource parsing. + +use craft_dxf::lin_pat::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat}; + +const LIN: &str = "\ +;; my own linetypes +*MYDASH,My dash __ __ __ +A,.5,-.25 + +*MYDOTS +A,0,-.1,0,-.2 +*MYTEXT,Text line --MY--MY-- +A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2 +*MYSHAPE,Shape line +A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1 +"; + +#[test] +fn simple_and_text_linetypes_are_read() { + let r = parse_lin(LIN); + let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]); + let dash = &r.items[0]; + assert_eq!(dash.description, "My dash __ __ __"); + assert_eq!(dash.pattern.iter().map(|e| e.length).collect::>(), [0.5, -0.25]); + assert_eq!(r.items[1].description, ""); + assert_eq!(r.items[1].pattern.len(), 4); + + // The text belongs to the gap before it: drawn at that gap's end. + let text = &r.items[2].pattern; + assert_eq!(text.len(), 3); + assert_eq!(text[1].length, -0.2); + assert_eq!(text[1].text.as_deref(), Some("MY")); + assert_eq!(text[1].style.as_deref(), Some("STANDARD")); + assert!((text[1].scale - 0.1).abs() < 1e-12); + assert!((text[1].offset[0] + 0.1).abs() < 1e-12 && (text[1].offset[1] + 0.05).abs() < 1e-12); + assert!(!text[1].absolute); + assert!(text[2].text.is_none()); + + // Shapes need SHX files: left out with a note, the dashes kept. + let shape = &r.items[3].pattern; + assert_eq!(shape.iter().map(|e| e.length).collect::>(), [0.25, -0.1, -0.1, 1.0]); + assert!(shape.iter().all(|e| e.text.is_none())); + assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings); +} + +#[test] +fn text_rotation_units_and_absolute_angles() { + let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let rot = |i: usize| r.items[i].pattern[0].rotation; + assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute); + assert!((rot(1) - 1.5).abs() < 1e-12); + assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12); + // Commas and brackets inside the quoted text are text. + assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]")); +} + +#[test] +fn broken_linetypes_are_skipped_with_warnings() { + let text = "\ +*NOPATTERN +*BADNUM +A,.5,abc +*BADALIGN +B,.5,-.5 +*UNCLOSED +A,.5,[\"x\",S1 +* +A,1,-1 +A,1,-1 +*GOOD +A,1,-1 +*GOOD +A,2,-2 +*ZERO +A,0,0 +*NOSTYLE +A,1,[\"x\"],-1 +"; + let r = parse_lin(text); + assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::>(), ["GOOD"]); + assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept"); + for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] { + assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings); + } +} + +#[test] +fn hostile_linetype_files_never_panic_and_stay_capped() { + let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(",")); + let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(",")); + let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect(); + let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n"; + for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"] + { + let r = parse_lin(text); + assert!(r.items.len() <= 4096); + assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite()))); + assert!(r.warnings.len() <= 101); + } + assert!(parse_lin(huge).items.is_empty()); + assert_eq!(parse_lin(&defs).items.len(), 4096); +} + +const PAT: &str = "\ +; my own patterns +*MYGRID, My grid +0, 0,0, 0,.5 +90, 0,0, 0,.5 +*MYBRICK,My brick ; trailing comment +0, 0,0, 0,.25 +90, 0,0, .25,.25, .25,-.25 +"; + +#[test] +fn hatch_patterns_are_read() { + let r = parse_pat(PAT); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(r.items.len(), 2); + let grid = &r.items[0]; + assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid")); + assert_eq!(grid.lines.len(), 2); + assert_eq!(grid.lines[1].angle, 90.0); + assert_eq!(grid.lines[1].delta, [0.0, 0.5]); + let brick = &r.items[1]; + assert_eq!(brick.description, "My brick"); + assert_eq!(brick.lines[1].origin, [0.0, 0.0]); + assert_eq!(brick.lines[1].dashes, [0.25, -0.25]); +} + +#[test] +fn lowercase_pattern_names_are_upper_cased() { + let r = parse_pat("*mypat\n45,0,0,0,.125\n"); + assert_eq!(r.items[0].name, "MYPAT"); +} + +#[test] +fn broken_patterns_are_skipped_with_warnings() { + let text = "\ +0,0,0,0,1 +*EMPTY +*SHORT +0,0,0 +*ZEROGAP +0,0,0,1,0 +*BADNUM +0,0,0,0,x +*OK +0,0,0,0,1 +*OK +45,0,0,0,1 +"; + let r = parse_pat(text); + assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::>(), ["OK"]); + assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept"); + for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] { + assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings); + } +} + +#[test] +fn hostile_pattern_files_never_panic_and_stay_capped() { + let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5)); + let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(",")); + let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(",")); + let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect(); + let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n"; + for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] { + let r = parse_pat(text); + assert!(r.items.len() <= 4096); + assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES))); + assert!(r.warnings.len() <= 101); + } + assert!(parse_pat(&families).items.is_empty()); + assert!(parse_pat(&dashes).items.is_empty()); + assert_eq!(parse_pat(&ok_dashes).items.len(), 1); + assert!(parse_pat(big).items.is_empty()); + assert_eq!(parse_pat(&defs).items.len(), 4096); +} diff --git a/crates/file-formats/src/lib.rs b/crates/file-formats/src/lib.rs index 38619075f..0c290d93d 100644 --- a/crates/file-formats/src/lib.rs +++ b/crates/file-formats/src/lib.rs @@ -39,6 +39,8 @@ pub enum Format { Cineon, Dicom, Iff, + /// JPEG-LS (ITU-T T.87). Its files start with the same `FF D8 FF` bytes as JPEG files. + JpegLs, Ase, Psd, Affinity, @@ -108,7 +110,7 @@ const fn availability(feature: bool, supported: bool) -> Availability { impl Format { /// Every known format, including formats whose reader or writer is not enabled in this build. - pub const ALL: [Format; 56] = [ + pub const ALL: [Format; 57] = [ Self::Pdf, Self::Eps, Self::PostScript, @@ -139,6 +141,7 @@ impl Format { Self::Cineon, Self::Dicom, Self::Iff, + Self::JpegLs, Self::Ase, Self::Psd, Self::Affinity, @@ -200,6 +203,7 @@ impl Format { Self::Cineon => &["cin"], Self::Dicom => &["dcm", "dicom", "dc3"], Self::Iff => &["iff", "lbm", "ilbm"], + Self::JpegLs => &["jls"], Self::Ase => &["ase"], Self::Psd => &["psd", "psb", "psdt"], Self::Affinity => &["afdesign", "afphoto", "afpub", "af"], @@ -270,6 +274,7 @@ impl Format { Self::Cineon => "image/x-cineon", Self::Dicom => "application/dicom", Self::Iff => "image/ilbm", + Self::JpegLs => "image/jls", Self::Ase => "application/x-adobe-swatch-exchange", Self::Psd => "image/vnd.adobe.photoshop", Self::Affinity => "application/x-affinity", @@ -327,6 +332,7 @@ impl Format { Self::Cineon => Codec::Cineon, Self::Dicom => Codec::Dicom, Self::Iff => Codec::Iff, + Self::JpegLs => Codec::JpegLs, _ => return None, }) } @@ -381,7 +387,8 @@ impl Format { | Self::Fits | Self::Dpx | Self::Cineon - | Self::Iff => capability(raster, true, true, false, false), + | Self::Iff + | Self::JpegLs => capability(raster, true, true, false, false), Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false), Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false), Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false), @@ -483,7 +490,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option { if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) { return Some(Format::Affinity); } - if let Some(raster) = raster_signature(bytes) { + if let Some(raster) = raster_signature(name, bytes) { return Some(raster); } if bytes.starts_with(b"silhouette04;") || bytes.starts_with(b"silhouette05;") { @@ -598,13 +605,18 @@ fn dxf_ascii_prefix(bytes: &[u8]) -> bool { matches!((lines.next(), lines.next(), lines.next(), lines.next()), (Some("0"), Some("SECTION"), Some("2"), Some(section)) if matches!(section, "HEADER" | "CLASSES" | "TABLES" | "BLOCKS" | "ENTITIES" | "OBJECTS")) } -fn raster_signature(bytes: &[u8]) -> Option { +fn raster_signature(name: &str, bytes: &[u8]) -> Option { let head = bytes.get(..16).unwrap_or(bytes); if head.starts_with(b"\x89PNG\r\n\x1a\n") { return Some(Format::Png); } if head.starts_with(b"\xff\xd8\xff") { - return Some(Format::Jpeg); + return Some(match jpeg_frame(bytes) { + JpegFrame::Ls => Format::JpegLs, + JpegFrame::Other => Format::Jpeg, + JpegFrame::Unknown if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("jls")) => Format::JpegLs, + JpegFrame::Unknown => Format::Jpeg, + }); } if head.starts_with(b"BM") { return Some(Format::Bmp); @@ -620,3 +632,50 @@ fn raster_signature(bytes: &[u8]) -> Option { } None } + +/// What the marker segments after a JPEG start-of-image marker lead to. +#[derive(Debug, PartialEq, Eq)] +enum JpegFrame { + /// An SOF55 frame header (`FF F7`, ITU-T T.87): JPEG-LS. + Ls, + /// Another frame header, a scan header, an end-of-image marker, or a byte that is not a + /// marker where one should be. + Other, + /// The bytes, or the probe's first 1 MiB, end before a frame or scan header. + Unknown, +} + +/// Walk the marker segments from the start-of-image marker to the first frame or scan header. +/// Only the first 1 MiB is read, and each step moves forward at least one byte. The walk follows +/// `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does +/// not link. +fn jpeg_frame(bytes: &[u8]) -> JpegFrame { + const LIMIT: usize = 1 << 20; + let bytes = bytes.get(..bytes.len().min(LIMIT)).unwrap_or(bytes); + let mut pos = 2; + loop { + let (Some(&prefix), Some(&marker)) = (bytes.get(pos), bytes.get(pos + 1)) else { + return if bytes.get(pos).is_none_or(|&prefix| prefix == 0xFF) { JpegFrame::Unknown } else { JpegFrame::Other }; + }; + if prefix != 0xFF { + return JpegFrame::Other; + } + match marker { + 0xF7 => return JpegFrame::Ls, + // `FF 00` is a stuffed zero, not a marker. + 0x00 | 0xDA | 0xD9 => return JpegFrame::Other, + // A DRI segment (`FF DD`) may come before an SOF55 frame header, so it is skipped + // by its length below. + 0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return JpegFrame::Other, + // A fill byte, or a marker without a length. + 0xFF => pos += 1, + 0x01 | 0xD0..=0xD7 => pos += 2, + _ => { + let Some(length) = bytes.get(pos + 2..pos + 4).map(|length| usize::from(u16::from_be_bytes([length[0], length[1]]))) else { + return JpegFrame::Unknown; + }; + pos += 2 + length; + } + } + } +} diff --git a/crates/file-formats/src/tests.rs b/crates/file-formats/src/tests.rs index 399f884ac..504eba727 100644 --- a/crates/file-formats/src/tests.rs +++ b/crates/file-formats/src/tests.rs @@ -57,6 +57,72 @@ fn bounded_probes_prefer_signatures_and_resolve_extensions() { assert_eq!(super::detect("unknown", b""), None); } +#[test] +fn jpeg_ls_is_told_from_jpeg_and_resolves_its_extension() { + assert_eq!(super::from_extension("JLS"), Some(Format::JpegLs)); + assert_eq!(Format::JpegLs.mime_type(), Some("image/jls")); + assert_eq!(super::detect("scan.jls", b""), Some(Format::JpegLs)); + // SOI followed by an SOF55 frame header. + assert_eq!(super::detect("scan.jpg", b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"), Some(Format::JpegLs)); + assert_eq!(super::detect("photo.jls", b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0"), Some(Format::Jpeg)); + // An APP0 segment, a fill byte and a DRI segment before the SOF55 frame header. + let with_segments = b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"; + assert_eq!(super::detect("scan.jpg", with_segments), Some(Format::JpegLs)); + assert_eq!(super::detect("", with_segments), Some(Format::JpegLs)); + // Bytes that end before any frame header: the name decides. + assert_eq!(super::detect("scan.jls", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::JpegLs)); + assert_eq!(super::detect("photo.jpg", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg)); + assert_eq!(super::detect("", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg)); +} + +#[test] +fn jpeg_marker_walk_reads_only_the_first_mebibyte() { + let mut bytes = vec![0xFF; (1 << 20) + 64]; + bytes[1] = 0xD8; + let len = bytes.len(); + bytes[len - 2] = 0xF7; + assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::Jpeg)); + assert_eq!(super::detect("scan.jls", &bytes), Some(Format::JpegLs)); + bytes[1 << 19] = 0xF7; + assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::JpegLs)); +} + +#[cfg(feature = "raster-codecs")] +#[test] +fn jpeg_marker_walk_matches_the_codec_detection() { + let cases: [&[u8]; 6] = [ + b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0", + b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0", + b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0", + b"\xff\xd8\xff\xd0\xff\x01\xff\xf7\0\x0b", + b"\xff\xd8\xff\xe0\0\x04\0\0\x12\x34", + b"\xff\xd8\xff\xda\0\x08", + ]; + for bytes in cases { + let expected = match craft_image_codecs::detect(bytes) { + Some(craft_image_codecs::Format::JpegLs) => Format::JpegLs, + _ => Format::Jpeg, + }; + assert_eq!(super::detect("", bytes), Some(expected), "{bytes:02x?}"); + } +} + +#[test] +fn jpeg_ls_capabilities_follow_the_codec() { + #[cfg(feature = "raster-codecs")] + { + assert_eq!(Format::JpegLs.raster_codec(), Some(craft_image_codecs::Format::JpegLs)); + assert_eq!(Format::JpegLs.extensions(), craft_image_codecs::Format::JpegLs.extensions()); + assert_eq!(Format::JpegLs.capabilities().read, Availability::Available); + assert_eq!(Format::JpegLs.capabilities().write, Availability::Available); + } + #[cfg(not(feature = "raster-codecs"))] + { + assert_eq!(Format::JpegLs.capabilities().read, Availability::BuildDisabled); + assert_eq!(Format::JpegLs.capabilities().write, Availability::BuildDisabled); + } +} + #[test] fn registered_mime_and_preferred_extensions_remain_distinct() { assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type()); diff --git a/crates/file-import/Cargo.toml b/crates/file-import/Cargo.toml index 011943521..ab4eb9c6f 100644 --- a/crates/file-import/Cargo.toml +++ b/crates/file-import/Cargo.toml @@ -18,5 +18,8 @@ kurbo = { workspace = true } thiserror = { workspace = true } vectorcraft-geom = { workspace = true } +[dev-dependencies] +craft-image-codecs = { workspace = true } + [lints] workspace = true diff --git a/crates/file-import/src/lib.rs b/crates/file-import/src/lib.rs index 195363da0..ebf5dc3d0 100644 --- a/crates/file-import/src/lib.rs +++ b/crates/file-import/src/lib.rs @@ -89,14 +89,15 @@ pub const CAPABILITIES: &[Capability] = &[ detected_formats: &[ craft_file_formats::Format::Png, craft_file_formats::Format::Jpeg, + craft_file_formats::Format::JpegLs, craft_file_formats::Format::Bmp, craft_file_formats::Format::Gif, craft_file_formats::Format::Tiff, craft_file_formats::Format::WebP, ], - extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"], + extensions: &["png", "jpg", "jpeg", "jls", "bmp", "gif", "tif", "tiff", "webp"], write_extensions: &["png", "jpg", "jpeg"], - mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"], + mime_types: &["image/png", "image/jpeg", "image/jls", "image/bmp", "image/gif", "image/tiff", "image/webp"], raster: true, vector: false, }, @@ -197,7 +198,7 @@ pub fn format_for(name: &str, bytes: &[u8]) -> Option { F::Pdf => Some(ImportFormat::Pdf), F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf), F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps), - F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster), + F::Png | F::Jpeg | F::JpegLs | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster), _ => None, } } @@ -402,4 +403,27 @@ mod format_tests { let bytes = b"%PDF-1.7\n/AIPrivateData"; assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf)); } + + #[test] + fn jpeg_ls_is_routed_to_the_raster_reader() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode}; + let gray: Vec = (0..6).map(|value| value * 40).collect(); + let Ok(image) = Image::from_u8(3, 2, ChannelLayout::Gray, gray.clone()) else { + panic!("a 3 by 2 gray image"); + }; + let Ok(bytes) = encode(&image, Format::JpegLs, &EncodeOptions::default()) else { + panic!("JPEG-LS encodes"); + }; + for name in ["scan.jls", "scan.jpg", "scan"] { + assert_eq!(format_for(name, &bytes), Some(ImportFormat::Raster), "{name}"); + let Ok(Imported::Raster(raster)) = import(name, &bytes, Limits::default()) else { + panic!("{name} imports as a raster image"); + }; + assert_eq!((raster.width, raster.height), (3, 2)); + let red: Vec = raster.rgba.as_chunks::<4>().0.iter().map(|pixel| pixel[0]).collect(); + assert_eq!(red, gray, "{name}"); + } + assert!(supported_formats(ImportFormat::Raster).contains(&craft_file_formats::Format::JpegLs)); + assert!(supported_extensions().contains(&"jls")); + } } diff --git a/crates/html/Cargo.toml b/crates/html/Cargo.toml index d4d1c4f0e..9119b0545 100644 --- a/crates/html/Cargo.toml +++ b/crates/html/Cargo.toml @@ -13,6 +13,8 @@ workspace = true [features] # HTML documents: read into and written from the craft-flow model and a craft-wordmodel Document. flow = ["dep:craft-codepage", "dep:craft-flow", "dep:craft-math", "dep:craft-mime", "dep:craft-wordmodel", "dep:encoding_rs"] +# Standalone portable HTML document writer. +standalone = ["dep:craft-mime"] [dependencies] craft-codepage = { workspace = true, optional = true } diff --git a/crates/html/src/lib.rs b/crates/html/src/lib.rs index 70f19746e..fa504882a 100644 --- a/crates/html/src/lib.rs +++ b/crates/html/src/lib.rs @@ -38,6 +38,8 @@ struct ReadmeExamples; pub mod doc; mod entity; mod lex; +#[cfg(feature = "standalone")] +pub mod standalone; pub use entity::{decode_entity, escape, escape_dq, reference, unescape, unescape_attr}; pub use lex::{Lexer, Limits, Options, Tag, Token}; diff --git a/crates/html/src/standalone.rs b/crates/html/src/standalone.rs new file mode 100644 index 000000000..ac7f89316 --- /dev/null +++ b/crates/html/src/standalone.rs @@ -0,0 +1,194 @@ +//! Portable standalone HTML document writer (no PDF layout, reading order, or export policy). + +pub use craft_mime::transfer::base64; + +/// Whether a character may appear in the output. XML 1.0 forbids the C0 controls other than tab, +/// line feed and carriage return, and U+FFFE/U+FFFF. +pub fn allowed(c: char) -> bool { + matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}') +} + +/// Escape text for HTML content and double-quoted attribute values, stripping disallowed characters. +pub fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars().filter(|c| allowed(*c)) { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + c => o.push(c), + } + } + o +} + +/// An inline run of text for portable HTML rendering. +pub struct HtmlRun<'a> { + pub text: &'a str, + pub bold: bool, + pub italic: bool, + pub color: [u8; 3], +} + +/// A single table cell for portable HTML rendering. +pub struct HtmlCell<'a> { + pub text: &'a str, + pub bold: bool, + pub italic: bool, + pub color: [u8; 3], + pub span: usize, +} + +/// A table of rows of cells for portable HTML rendering. +pub struct HtmlTable<'a> { + pub rows: Vec>>, +} + +/// A block-level element in a portable HTML document. +pub enum HtmlBlock<'a> { + Para { runs: Vec>, level: u8 }, + Table(HtmlTable<'a>), + Image { mime: &'a str, bytes: &'a [u8] }, + PageBreak, +} + +fn rgb_hex(rgb: [u8; 3]) -> Option { + let [r, g, b] = rgb; + (r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}")) +} + +fn style_color(rgb: [u8; 3], simple: bool) -> String { + if simple { String::new() } else { rgb_hex(rgb).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) } +} + +/// Wrap escaped inline text in `` and/or `` when non-whitespace. +pub fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String { + if text.trim().is_empty() { + return text; + } + if italic { + text = format!("{text}"); + } + if bold { + text = format!("{text}"); + } + text +} + +/// Render a paragraph or heading (`lvl` clamped to `1..=6`, or `0` for `

`). +pub fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option { + let non_empty: Vec<_> = runs.iter().map(|r| (r, esc(r.text))).filter(|(_, text)| !text.is_empty()).collect(); + let &(first, _) = non_empty.iter().find(|(_, text)| !text.trim().is_empty())?; + let mut t = String::new(); + for (run, text) in non_empty { + if text.trim().is_empty() { + t.push_str(&text); + continue; + } + let mut out = wrap_inline(text, run.bold && lvl == 0, run.italic); + // The paragraph has its first visible run's colour; a run in another colour says so. + if !simple && run.color != first.color { + let [red, green, blue] = run.color; + out = format!("{out}"); + } + t.push_str(&out); + } + let style = style_color(first.color, simple); + Some(match lvl.min(6) { + 0 => format!("{t}

\n"), + l => format!("{t}\n"), + }) +} + +/// Render a table into an HTML `` element. +pub fn render_table(t: &HtmlTable<'_>, simple: bool) -> String { + let mut s = String::from("
\n"); + for row in &t.rows { + s.push_str(""); + for c in row { + let body = wrap_inline(esc(c.text), c.bold, c.italic); + let span = if c.span > 1 { format!(" colspan=\"{}\"", c.span) } else { String::new() }; + let style = style_color(c.color, simple); + s.push_str(&format!("{body}")); + } + s.push_str("\n"); + } + s.push_str("
\n"); + s +} + +/// Render a sequence of portable HTML blocks into a standalone HTML5 document. +pub fn render(blocks: &[HtmlBlock<'_>], title: &str, simple: bool, language: Option<&str>) -> String { + let lang = language.map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default(); + let mut s = format!( + "\n\n\n\n{}\n{}\n\n\n", + esc(title), + if simple { + "" + } else { + "" + } + ); + for block in blocks { + match block { + HtmlBlock::Para { runs, level } => { + if let Some(p) = render_para(runs, *level, simple) { + s.push_str(&p); + } + } + HtmlBlock::Table(t) => s.push_str(&render_table(t, simple)), + HtmlBlock::Image { mime, bytes } => { + s.push_str(&format!("

\"\"

\n", esc(mime), base64(bytes))); + } + HtmlBlock::PageBreak => s.push_str("
\n"), + } + } + s.push_str("\n\n"); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renders_standalone_document_and_omits_empty_runs() { + let blocks = [ + HtmlBlock::Para { + runs: vec![ + HtmlRun { text: "\u{1}\u{FFFF}", bold: true, italic: true, color: [255, 0, 0] }, + HtmlRun { text: "Hello", bold: false, italic: false, color: [0, 128, 0] }, + ], + level: 0, + }, + HtmlBlock::PageBreak, + HtmlBlock::Table(HtmlTable { + rows: vec![vec![ + HtmlCell { text: "\u{1}", bold: true, italic: true, color: [0, 0, 0], span: 1 }, + HtmlCell { text: "Val", bold: true, italic: false, color: [0, 0, 0], span: 2 }, + ]], + }), + ]; + let out = render(&blocks, "Clean ", false, Some("en-US")); + assert!(out.starts_with("<!DOCTYPE html>\n<html lang=\"en-US\">\n"), "{out}"); + assert!(out.contains("<title>Clean <Title>"), "{out}"); + assert!(out.contains("

Hello

"), "{out}"); + assert!(out.contains("
\n"), "{out}"); + assert!(out.contains("Val"), "{out}"); + } + + #[test] + fn heading_level_clamps_to_h6() { + let runs = [HtmlRun { text: "Deep", bold: true, italic: false, color: [0, 0, 0] }]; + assert_eq!(render_para(&runs, 9, true).as_deref(), Some("
Deep
\n")); + } + + #[test] + fn image_mime_is_attribute_escaped() { + let blocks = [HtmlBlock::Image { mime: "image/png\" onerror=\"alert(1)", bytes: b"abc" }]; + let out = render(&blocks, "Img", true, None); + assert!(out.contains("src=\"data:image/png" onerror="alert(1);base64,YWJj\""), "{out}"); + assert!(!out.contains("onerror=\"alert(1)\""), "{out}"); + } +} diff --git a/crates/idml/src/model/document.rs b/crates/idml/src/model/document.rs index 830b95a3f..c66840a15 100644 --- a/crates/idml/src/model/document.rs +++ b/crates/idml/src/model/document.rs @@ -2,7 +2,13 @@ use craft_xml::El; -use super::{AlternatingFillValues, AlternatingStrokeValues, Spread, Story, StrokeValues, Values}; +use super::{AlternatingFillValues, AlternatingStrokeValues, MojikumiRow, Spread, Story, StrokeValues, Values}; +use crate::value::{escape_id, num}; +use crate::{prop, with_props}; + +fn bool_str(value: bool) -> &'static str { + if value { "true" } else { "false" } +} /// One IDML table-of-contents style entry before document style names are resolved. #[derive(Clone, Debug, Default, PartialEq)] @@ -190,6 +196,20 @@ impl ConditionValues { visible: values.get("Visible") != Some("false"), } } + + /// Emits a `Condition` element from these metadata values. + pub fn to_el(&self) -> El { + let name = self.name.as_deref().unwrap_or(""); + let self_id = self.self_id.clone().unwrap_or_else(|| format!("Condition/{}", escape_id(name))); + let rgb = self.indicator_rgb.unwrap_or([0, 0, 0]); + El::new("Condition") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("IndicatorColor", format!("{} {} {}", rgb[0], rgb[1], rgb[2])) + .with_attr("IndicatorMethod", "UseUnderline") + .with_attr("UnderlineIndicatorAppearance", "Solid") + .with_attr("Visible", bool_str(self.visible)) + } } /// Parsed IDML numbering-list metadata. @@ -292,6 +312,11 @@ impl TableStyleValues { } impl NumberingListValues { + /// The default IDML numbering list (`$ID/[Default]`). + pub fn default_list() -> Self { + Self { name: "$ID/[Default]".into(), continue_across_stories: false } + } + /// Reads a `NumberingList` element. pub fn from_el(el: &El) -> Self { let values = Values::of(el); @@ -300,6 +325,15 @@ impl NumberingListValues { continue_across_stories: values.boolean("ContinueNumbersAcrossStories") == Some(true), } } + + /// Emits a `NumberingList` element. + pub fn to_el(&self) -> El { + El::new("NumberingList") + .with_attr("Self", format!("NumberingList/{}", escape_id(&self.name))) + .with_attr("Name", &self.name) + .with_attr("ContinueNumbersAcrossStories", bool_str(self.continue_across_stories)) + .with_attr("ContinueNumbersAcrossDocuments", "false") + } } impl EpubSplitValues { @@ -355,6 +389,302 @@ impl TextVariableValues { kind, } } + + /// Emits a `TextVariable` element with its type-specific preference child. + pub fn to_el(&self) -> El { + let pref = |name: &str| El::new(name).with_attr("TextBefore", &self.before); + let (ty, settings) = match &self.kind { + TextVariableKind::CustomText { text } => ("CustomTextType", Some(pref("CustomTextVariablePreference").with_attr("Contents", text))), + TextVariableKind::LastPageNumber { section } => ( + "LastPageNumberType", + Some( + pref("PageNumberVariablePreference") + .with_attr("Format", "Current") + .with_attr("Scope", if *section { "SectionScope" } else { "DocumentScope" }), + ), + ), + TextVariableKind::ChapterNumber => ("ChapterNumberType", Some(pref("ChapterNumberVariablePreference").with_attr("Format", "Current"))), + TextVariableKind::FileName { extension } => ( + "FileNameType", + Some(pref("FileNameVariablePreference").with_attr("IncludePath", "false").with_attr("IncludeExtension", bool_str(*extension))), + ), + TextVariableKind::Date { kind, format } => { + let ty = match kind { + TextDateKind::Creation => "CreationDateType", + TextDateKind::Modification => "ModificationDateType", + TextDateKind::Output => "OutputDateType", + }; + (ty, Some(pref("DateVariablePreference").with_attr("Format", format))) + } + TextVariableKind::RunningHeader { style, character, last_on_page } => { + let (ty, el, key) = if *character { + ("MatchCharacterStyleType", "MatchCharacterStylePreference", "AppliedCharacterStyle") + } else { + ("MatchParagraphStyleType", "MatchParagraphStylePreference", "AppliedParagraphStyle") + }; + let strategy = if *last_on_page { "LastOnPage" } else { "FirstOnPage" }; + ( + ty, + Some( + pref(el) + .with_attr(key, style) + .with_attr("SearchStrategy", strategy) + .with_attr("ChangeCase", "None") + .with_attr("DeleteEndPunctuation", "false"), + ), + ) + } + TextVariableKind::CrossReference { page_number } => (if *page_number { "XrefPageNumberType" } else { "XrefChapterNumberType" }, None), + TextVariableKind::Imported { variable_type, settings_element, settings } => { + let el = (!settings_element.is_empty()).then(|| El { name: settings_element.clone(), attrs: settings.clone(), children: Vec::new() }); + (variable_type.as_str(), el) + } + }; + let self_id = self.self_id.clone().unwrap_or_else(|| format!("dTextVariablen{}", self.name)); + let mut el = El::new("TextVariable").with_attr("Self", self_id).with_attr("Name", &self.name).with_attr("VariableType", ty); + if let Some(mut s) = settings { + if !matches!(self.kind, TextVariableKind::Imported { .. }) { + s.set_attr("TextAfter", &self.after); + } + el.push(s); + } + el + } +} + +/// The standard `[No Language]` and `English: USA` `Language` elements emitted in `designmap.xml`. +pub fn default_languages() -> [El; 2] { + [ + El::new("Language") + .with_attr("Self", "Language/$ID/[No Language]") + .with_attr("Name", "$ID/[No Language]") + .with_attr("SingleQuotes", "''") + .with_attr("DoubleQuotes", "\"\"") + .with_attr("PrimaryLanguageName", "$ID/[No Language]") + .with_attr("SublanguageName", "$ID/[No Language]") + .with_attr("Id", "0") + .with_attr("HyphenationVendor", "$ID/") + .with_attr("SpellingVendor", "$ID/"), + El::new("Language") + .with_attr("Self", "Language/$ID/English%3a USA") + .with_attr("Name", "$ID/English: USA") + .with_attr("SingleQuotes", "\u{2018}\u{2019}") + .with_attr("DoubleQuotes", "\u{201C}\u{201D}") + .with_attr("PrimaryLanguageName", "$ID/English") + .with_attr("SublanguageName", "$ID/USA") + .with_attr("Id", "269") + .with_attr("HyphenationVendor", "Hunspell") + .with_attr("SpellingVendor", "Hunspell"), + ] +} + +/// The built-in cross-reference chapter/page number `TextVariable` elements. +pub fn default_xref_text_variables() -> [El; 2] { + [("XRefChapterNumber", "XrefChapterNumberType"), ("XRefPageNumber", "XrefPageNumberType")].map(|(name, ty)| { + let full_name = format!("TV {name}"); + El::new("TextVariable").with_attr("Self", format!("dTextVariablen{full_name}")).with_attr("Name", &full_name).with_attr("VariableType", ty) + }) +} + +/// Reusable IDML `KinsokuTable` schema values. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct KinsokuTableValues { + pub name: String, + pub cant_begin_line_chars: String, + pub cant_end_line_chars: String, + pub cant_be_separated_chars: String, + pub hanging_punctuation_chars: String, +} + +impl KinsokuTableValues { + /// Emits a `KinsokuTable` element. + pub fn to_el(&self) -> El { + El::new("KinsokuTable") + .with_attr("Self", format!("KinsokuTable/{}", escape_id(&self.name))) + .with_attr("Name", &self.name) + .with_attr("CantBeginLineChars", &self.cant_begin_line_chars) + .with_attr("CantEndLineChars", &self.cant_end_line_chars) + .with_attr("CantBeSeparatedChars", &self.cant_be_separated_chars) + .with_attr("HangingPunctuationChars", &self.hanging_punctuation_chars) + } +} + +/// Reusable IDML `MojikumiTable` schema values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MojikumiTableValues { + pub name: String, + pub based_on: String, + pub overrides: Vec, +} + +impl MojikumiTableValues { + /// Emits a `MojikumiTable` element with optional spacing overrides. + pub fn to_el(&self) -> El { + let mut el = El::new("MojikumiTable").with_attr("Self", format!("MojikumiTable/{}", escape_id(&self.name))).with_attr("Name", &self.name); + if !self.based_on.is_empty() { + el.set_attr("BasedOnMojikumiSet", &self.based_on); + } + if !self.overrides.is_empty() { + let mut list = El::new("OverrideMojikumiAkiList"); + for r in &self.overrides { + list.push( + El::new("OverrideMojikumiAkiType") + .with_attr("TargetMojikumiClass", r.target_class.to_string()) + .with_attr("SideMojikumiClass", r.side_class.to_string()) + .with_attr("SideIsAfterTarget", bool_str(r.after)) + .with_attr("Minimum", num(r.minimum)) + .with_attr("Desired", num(r.desired)) + .with_attr("Maximum", num(r.maximum)) + .with_attr("CompressionPriority", r.priority.to_string()) + .with_attr("AkiDoesNotFloat", bool_str(r.does_not_float)), + ); + } + let mut props = El::new("Properties"); + props.push(list); + el.push(props); + } + el + } +} + +/// IDML `LayerColor` property value: either a named enumeration or an RGB triplet. +#[derive(Clone, Debug, PartialEq)] +pub enum LayerColorValue { + Named(String), + Rgb([f64; 3]), +} + +/// Reusable IDML `Layer` schema values. +#[derive(Clone, Debug, PartialEq)] +pub struct LayerValues { + pub self_id: String, + pub name: String, + pub visible: bool, + pub locked: bool, + pub ignore_wrap: bool, + pub show_guides: bool, + pub lock_guides: bool, + pub printable: bool, + pub color: LayerColorValue, +} + +impl LayerValues { + /// Emits a `Layer` element with its `` child. + pub fn to_el(&self) -> El { + let color = match &self.color { + LayerColorValue::Named(name) => prop("LayerColor", "enumeration", name), + LayerColorValue::Rgb(rgb) => { + let mut el = El::new("LayerColor").with_attr("type", "list"); + for c in rgb { + el.push(prop("ListItem", "double", num(*c))); + } + el + } + }; + let el = El::new("Layer") + .with_attr("Self", &self.self_id) + .with_attr("Name", &self.name) + .with_attr("Visible", bool_str(self.visible)) + .with_attr("Locked", bool_str(self.locked)) + .with_attr("IgnoreWrap", bool_str(self.ignore_wrap)) + .with_attr("ShowGuides", bool_str(self.show_guides)) + .with_attr("LockGuides", bool_str(self.lock_guides)) + .with_attr("UI", "true") + .with_attr("Expendable", "true") + .with_attr("Printable", bool_str(self.printable)); + with_props(el, vec![color]) + } +} + +/// Reusable IDML `Section` schema values. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SectionValues { + pub self_id: String, + pub length: usize, + pub name: String, + pub continue_numbering: bool, + pub include_section_prefix: bool, + pub page_number_start: Option, + pub marker: String, + pub page_start: String, + pub section_prefix: String, + pub alternate_layout: Option<(String, usize)>, + pub page_number_style: String, +} + +impl SectionValues { + /// Emits a `Section` element with its `` child. + pub fn to_el(&self) -> El { + let mut el = El::new("Section") + .with_attr("Self", &self.self_id) + .with_attr("Length", self.length.to_string()) + .with_attr("Name", &self.name) + .with_attr("ContinueNumbering", bool_str(self.continue_numbering)) + .with_attr("IncludeSectionPrefix", bool_str(self.include_section_prefix)); + if let Some(n) = self.page_number_start { + el.set_attr("PageNumberStart", n.to_string()); + } + el = el.with_attr("Marker", &self.marker).with_attr("PageStart", &self.page_start).with_attr("SectionPrefix", &self.section_prefix); + if let Some((layout, layout_len)) = &self.alternate_layout { + el = el.with_attr("AlternateLayout", layout).with_attr("AlternateLayoutLength", layout_len.to_string()); + } + with_props(el, vec![prop("PageNumberStyle", "enumeration", &self.page_number_style)]) + } +} + +/// Emits a `HyperlinkURLDestination` element. +pub fn hyperlink_url_destination_el(self_id: &str, name: &str, url: &str) -> El { + El::new("HyperlinkURLDestination") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("DestinationURL", url) + .with_attr("Hidden", "false") +} + +/// Emits a `HyperlinkPageDestination` element. +pub fn hyperlink_page_destination_el(self_id: &str, name: &str, destination_page: &str) -> El { + El::new("HyperlinkPageDestination") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("DestinationPage", destination_page) + .with_attr("ViewSetting", "FitPage") + .with_attr("Hidden", "false") +} + +/// Emits a `HyperlinkPageItemSource` element. +pub fn hyperlink_page_item_source_el(self_id: &str, name: &str, source_page_item: &str) -> El { + El::new("HyperlinkPageItemSource") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("SourcePageItem", source_page_item) + .with_attr("Hidden", "false") +} + +/// Emits a `Hyperlink` element joining `source` and `destination`. +pub fn hyperlink_el(self_id: &str, name: &str, source: &str, destination: &str, visible: bool, destination_unique_key: u64) -> El { + let el = El::new("Hyperlink") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("Source", source) + .with_attr("Visible", bool_str(visible)) + .with_attr("Highlight", "None") + .with_attr("Width", "Thin") + .with_attr("BorderStyle", "Solid") + .with_attr("Hidden", "false") + .with_attr("DestinationUniqueKey", (destination_unique_key & 0xFFFF_FFFF).to_string()); + with_props(el, vec![prop("Destination", "object", destination)]) +} + +/// Emits the root `ColorGroup` (`ColorGroup/[Root Color Group]`) with `ColorGroupSwatch` children. +pub fn root_color_group_el(swatch_ids: &[String], swatch_id_prefix: &str) -> El { + let mut cg = El::new("ColorGroup") + .with_attr("Self", "ColorGroup/[Root Color Group]") + .with_attr("Name", "[Root Color Group]") + .with_attr("IsRootColorGroup", "true"); + for (n, id) in swatch_ids.iter().enumerate() { + cg.push(El::new("ColorGroupSwatch").with_attr("Self", format!("{swatch_id_prefix}ColorGroupSwatch{n:x}")).with_attr("SwatchItemRef", id)); + } + cg } impl TocStyleValues { diff --git a/crates/idml/src/model/mod.rs b/crates/idml/src/model/mod.rs index a4560b22e..99fb8a12f 100644 --- a/crates/idml/src/model/mod.rs +++ b/crates/idml/src/model/mod.rs @@ -22,8 +22,10 @@ mod story; use craft_xml::{El, Local, Node}; pub use document::{ - CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, ModelDocument, NumberingListValues, - TableStyleValues, TextDateKind, TextVariableKind, TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, + CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, KinsokuTableValues, LayerColorValue, + LayerValues, ModelDocument, MojikumiTableValues, NumberingListValues, SectionValues, TableStyleValues, TextDateKind, TextVariableKind, + TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, default_languages, default_xref_text_variables, + hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el, hyperlink_url_destination_el, root_color_group_el, }; pub use effects::{ DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting, diff --git a/crates/idml/tests/model.rs b/crates/idml/tests/model.rs index 075a77c82..e6fcc8f3f 100644 --- a/crates/idml/tests/model.rs +++ b/crates/idml/tests/model.rs @@ -280,3 +280,131 @@ fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values let variable = craft_idml::model::TextVariableValues::from_el(&legacy); assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); } + +#[test] +fn designmap_schema_elements_roundtrip_expected_attributes() { + use craft_idml::model::{ + ConditionValues, KinsokuTableValues, MojikumiRow, MojikumiTableValues, NumberingListValues, TextDateKind, TextVariableKind, + TextVariableValues, default_languages, default_xref_text_variables, + }; + + let langs = default_languages(); + assert_eq!(langs[0].attr("Self"), Some("Language/$ID/[No Language]")); + assert_eq!(langs[1].attr("Self"), Some("Language/$ID/English%3a USA")); + assert_eq!(langs[1].attr("Id"), Some("269")); + + let num_list = NumberingListValues::default_list().to_el(); + assert_eq!(num_list.attr("Self"), Some("NumberingList/$ID/[Default]")); + assert_eq!(num_list.attr("ContinueNumbersAcrossDocuments"), Some("false")); + + let kinsoku = KinsokuTableValues { + name: "My:Kinsoku".into(), + cant_begin_line_chars: "。".into(), + cant_end_line_chars: "「".into(), + cant_be_separated_chars: "…".into(), + hanging_punctuation_chars: "、".into(), + } + .to_el(); + assert_eq!(kinsoku.attr("Self"), Some("KinsokuTable/My%3aKinsoku")); + assert_eq!(kinsoku.attr("CantBeginLineChars"), Some("。")); + + let mojikumi = MojikumiTableValues { + name: "Custom%1".into(), + based_on: "Base".into(), + overrides: vec![MojikumiRow { + target_class: 1, + side_class: 2, + after: true, + minimum: 0.0, + desired: 0.25, + maximum: 0.5, + priority: 3, + does_not_float: false, + }], + } + .to_el(); + assert_eq!(mojikumi.attr("Self"), Some("MojikumiTable/Custom%251")); + assert_eq!(mojikumi.attr("BasedOnMojikumiSet"), Some("Base")); + let row = mojikumi.child("Properties").and_then(|p| p.child("OverrideMojikumiAkiList")).and_then(|l| l.child("OverrideMojikumiAkiType")).unwrap(); + assert_eq!(row.attr("TargetMojikumiClass"), Some("1")); + assert_eq!(row.attr("SideIsAfterTarget"), Some("true")); + + let cond = ConditionValues { self_id: None, name: Some("A:B".into()), indicator_rgb: Some([10, 20, 30]), visible: true }.to_el(); + assert_eq!(cond.attr("Self"), Some("Condition/A%3aB")); + assert_eq!(cond.attr("IndicatorColor"), Some("10 20 30")); + assert_eq!(cond.attr("Visible"), Some("true")); + + let xrefs = default_xref_text_variables(); + assert_eq!(xrefs[0].attr("VariableType"), Some("XrefChapterNumberType")); + assert_eq!(xrefs[1].attr("VariableType"), Some("XrefPageNumberType")); + + let tv = TextVariableValues { + self_id: None, + name: "Mod".into(), + before: "Updated ".into(), + after: "!".into(), + kind: TextVariableKind::Date { kind: TextDateKind::Modification, format: "yyyy-MM-dd".into() }, + } + .to_el(); + assert_eq!(tv.attr("VariableType"), Some("ModificationDateType")); + let pref = tv.child("DateVariablePreference").unwrap(); + assert_eq!(pref.attr("TextBefore"), Some("Updated ")); + assert_eq!(pref.attr("TextAfter"), Some("!")); + assert_eq!(pref.attr("Format"), Some("yyyy-MM-dd")); +} + +#[test] +fn designmap_layers_sections_and_hyperlinks_roundtrip_expected_attributes() { + use craft_idml::model::{ + LayerColorValue, LayerValues, SectionValues, hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el, + hyperlink_url_destination_el, root_color_group_el, + }; + + let layer = LayerValues { + self_id: "u1".into(), + name: "Layer 1".into(), + visible: true, + locked: false, + ignore_wrap: false, + show_guides: true, + lock_guides: false, + printable: true, + color: LayerColorValue::Rgb([128.0, 64.0, 0.0]), + } + .to_el(); + assert_eq!(layer.attr("Self"), Some("u1")); + assert_eq!(layer.attr("UI"), Some("true")); + let list_items: Vec<_> = + layer.child("Properties").and_then(|p| p.child("LayerColor")).map(|lc| lc.elements().map(|e| e.deep_text()).collect()).unwrap(); + assert_eq!(list_items, ["128", "64", "0"]); + + let section = SectionValues { + self_id: "u2".into(), + length: 4, + name: "A".into(), + continue_numbering: false, + include_section_prefix: true, + page_number_start: Some(1), + marker: "M".into(), + page_start: "u3".into(), + section_prefix: "A".into(), + alternate_layout: Some(("Phone".into(), 4)), + page_number_style: "Arabic".into(), + } + .to_el(); + assert_eq!(section.attr("PageNumberStart"), Some("1")); + assert_eq!(section.attr("AlternateLayout"), Some("Phone")); + + let url_dest = hyperlink_url_destination_el("HyperlinkURLDestination/u1", "Site", "https://example.com"); + assert_eq!(url_dest.attr("DestinationURL"), Some("https://example.com")); + let page_dest = hyperlink_page_destination_el("HyperlinkPageDestination/p1", "Page", "u3"); + assert_eq!(page_dest.attr("ViewSetting"), Some("FitPage")); + let item_src = hyperlink_page_item_source_el("HyperlinkPageItemSource/i1k0", "Link", "u4"); + assert_eq!(item_src.attr("SourcePageItem"), Some("u4")); + let link = hyperlink_el("u5", "Link", "HyperlinkPageItemSource/i1k0", "HyperlinkURLDestination/u1", true, 0x1_0000_0007); + assert_eq!(link.attr("DestinationUniqueKey"), Some("7")); + + let cg = root_color_group_el(&["Color/Black".into(), "Color/Paper".into()], "u10"); + assert_eq!(cg.attr("IsRootColorGroup"), Some("true")); + assert_eq!(cg.elements().count(), 2); +} diff --git a/crates/image-codecs/src/codecs/exr.rs b/crates/image-codecs/src/codecs/exr.rs index 04019bcdc..87c961779 100644 --- a/crates/image-codecs/src/codecs/exr.rs +++ b/crates/image-codecs/src/codecs/exr.rs @@ -402,9 +402,21 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result JpegMeta { } let seg = &b[i + 4..i + 2 + len]; match marker { - 0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") => { + 0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") && jfif_dpi.is_none() => { let unit = seg[7]; let x = u16::from_be_bytes([seg[8], seg[9]]) as f32; let y = u16::from_be_bytes([seg[10], seg[11]]) as f32; @@ -278,9 +278,10 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { } m.held_coefficients = sof.map_or(0, |(marker, seg)| held_coefficients(marker, seg, scan_components)); m.dpi = photoshop_resolution(&photoshop) - .or_else(|| m.xmp.as_deref().and_then(xmp_resolution)) - .or_else(|| m.exif.as_deref().and_then(exif_resolution)) - .or(jfif_dpi); + .filter(|&d| crate::resolution_probe::usable(d)) + .or_else(|| m.xmp.as_deref().and_then(xmp_resolution).filter(|&d| crate::resolution_probe::usable(d))) + .or_else(|| m.exif.as_deref().and_then(exif_resolution).filter(|&d| crate::resolution_probe::usable(d))) + .or_else(|| jfif_dpi.filter(|&d| crate::resolution_probe::usable(d))); m.photoshop = Some(photoshop).filter(|p| !p.is_empty()); if !icc_parts.is_empty() { icc_parts.sort_by_key(|p| p.0); diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index b4436055c..af0769c96 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -276,6 +276,9 @@ pub struct EncodeOptions { /// the full image, which comes first. pub tiff_pyramid: bool, pub exr_compression: ExrCompression, + /// OpenEXR `chromaticities` attribute (`[red, green, blue, white]` CIE xy), written into the + /// image header when set. + pub exr_chromaticities: Option<[[f32; 2]; 4]>, /// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise. pub dpx_bits: Option, /// DDS compression and mip chain. @@ -302,6 +305,7 @@ impl Default for EncodeOptions { tiff_bigtiff: false, tiff_pyramid: false, exr_compression: ExrCompression::Zip16, + exr_chromaticities: None, dpx_bits: None, dds: DdsOptions::default(), embed_icc: true, diff --git a/crates/image-codecs/src/resolution_probe.rs b/crates/image-codecs/src/resolution_probe.rs index f7b9aff83..87729f18e 100644 --- a/crates/image-codecs/src/resolution_probe.rs +++ b/crates/image-codecs/src/resolution_probe.rs @@ -17,7 +17,7 @@ //! non-positive or past [`MAX_PPI`] gives `None`, so the caller keeps its own default. use crate::Limits; -use crate::codecs::{jpeg, png, webp}; +use crate::codecs::{jpeg, png}; use crate::resolution::exif_resolution; /// Resolutions above this many pixels per inch are treated as corrupt. @@ -102,10 +102,28 @@ fn png_exif(bytes: &[u8]) -> Option<(f32, f32)> { exif_resolution(&exif?) } -/// The resolution of a WebP's `EXIF` chunk, read by the decoder's own container probe. +/// The resolution of a WebP's `EXIF` chunk, read from the RIFF container within its declared size. fn webp_exif(bytes: &[u8]) -> Option<(f32, f32)> { - let (_, _, exif) = webp::probe(bytes, &Limits::default()).ok()?; - exif_resolution(&exif?) + let riff = usize::try_from(le_u32(bytes, 4)?).ok()?; + let end = 8usize.checked_add(riff)?.min(bytes.len()); + let mut pos = 12usize; + for _ in 0..MAX_CHUNKS { + let kind = bytes.get(pos..pos.checked_add(4)?)?; + let size = usize::try_from(le_u32(bytes, pos.checked_add(4)?)?).ok()?; + let data = pos.checked_add(8)?; + if data.checked_add(size)? > end { + return None; + } + if kind == b"EXIF" { + let exif = bytes.get(data..data + size)?; + let tiff = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + if let Some(dpi) = exif_resolution(tiff).filter(|&d| usable(d)) { + return Some(dpi); + } + } + pos = data.checked_add(size.checked_add(size & 1)?)?; + } + None } /// BMP: the info header size at 14 (40 or more for a header with resolution fields), then the diff --git a/crates/image-codecs/src/resolution_probe_tests.rs b/crates/image-codecs/src/resolution_probe_tests.rs index 65a797853..1a650ec3f 100644 --- a/crates/image-codecs/src/resolution_probe_tests.rs +++ b/crates/image-codecs/src/resolution_probe_tests.rs @@ -124,7 +124,15 @@ fn jpeg_exif_wins_over_jfif_and_non_exif_app1_is_skipped() { assert_eq!(file_resolution(&jpeg(&[jfif(1, 72, 72), xmp.clone(), exif])), Some((600.0, 600.0))); // An unusable EXIF value falls back to JFIF. let zero = exif_app1(&tiff(true, 0, 0, None)); - assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, zero])), Some((96.0, 96.0))); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp.clone(), zero])), Some((96.0, 96.0))); + let huge = exif_app1(&tiff(true, 1_000_000, 1_000_000, None)); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), huge])), Some((96.0, 96.0))); + // Sub-1.0 EXIF rational also falls back to JFIF. + let mut sub = tiff(true, 1, 1, None); + let len = sub.len(); + sub[len - 12..len - 8].copy_from_slice(&4u32.to_le_bytes()); + sub[len - 4..len].copy_from_slice(&4u32.to_le_bytes()); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, exif_app1(&sub)])), Some((96.0, 96.0))); } #[test] @@ -166,6 +174,35 @@ fn webp_without_exif_has_none() { assert_eq!(file_resolution(b"RIFF\x04\0\0\0WEBP"), None); } +#[test] +fn webp_exif_after_many_frames_and_riff_bounds() { + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend_from_slice(kind); + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_le_bytes()); + out.extend_from_slice(data); + if data.len() % 2 == 1 { + out.push(0); + } + }; + let mut body = b"WEBP".to_vec(); + chunk(&mut body, b"VP8X", &[0; 10]); + chunk(&mut body, b"ANIM", &[0; 6]); + for _ in 0..100 { + chunk(&mut body, b"ANMF", &[0; 17]); + } + chunk(&mut body, b"EXIF", &tiff(true, 300, 300, Some(2))); + let riff = |size: usize, trailing: usize| { + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&u32::try_from(size).unwrap().to_le_bytes()); + webp.extend_from_slice(&body); + webp.extend_from_slice(&vec![0xAA; trailing]); + webp + }; + assert_eq!(file_resolution(&riff(body.len(), 0)), Some((300.0, 300.0))); + assert_eq!(file_resolution(&riff(body.len(), 4)), Some((300.0, 300.0))); + assert_eq!(file_resolution(&riff(body.len() - 4, 4)), None); +} + #[test] fn bmp_pixels_per_metre() { close(file_resolution(&bmp(40, 3_780, 7_559)), (96.0, 192.0)); diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs index e0d064da5..17f04fe63 100644 --- a/crates/mcp-server/src/server.rs +++ b/crates/mcp-server/src/server.rs @@ -243,6 +243,10 @@ impl Server { }; return Some(error(echoed, INVALID_REQUEST, "missing `method`")); }; + // A malformed envelope must not dispatch a tool or change notification state. + if o.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { + return Some(error(Value::Null, INVALID_REQUEST, "`jsonrpc` must be \"2.0\"")); + } let params = o.get("params").cloned().unwrap_or(Value::Null); let Some(id) = id else { if method == "notifications/initialized" { diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs index 3f8f8d315..bf273c81e 100644 --- a/crates/mcp-server/src/tests.rs +++ b/crates/mcp-server/src/tests.rs @@ -48,6 +48,63 @@ fn serve_with(tools: T, lines: &[Value]) -> (Server, Vec) { (s, replies) } +fn malformed_version_messages() -> Vec { + let mut messages = Vec::new(); + for version in [None, Some(Value::Null), Some(json!("1.0")), Some(json!(2.0)), Some(json!(true)), Some(json!([])), Some(json!({}))] { + for mut message in [ + json!({"id": 1, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "changed"}}}), + json!({"method": "notifications/initialized"}), + ] { + if let Some(version) = &version { + message["jsonrpc"] = version.clone(); + } + messages.push(message); + } + } + messages +} + +fn invalid_version_reply() -> Value { + json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "`jsonrpc` must be \"2.0\""}}) +} + +/// Invalid envelopes are refused before listing or calling tools or changing lifecycle state. +#[test] +fn invalid_jsonrpc_versions_never_dispatch() { + for message in malformed_version_messages() { + let mut s = Server::new(info(), Echo::default()); + let response = s.handle(message.clone()).unwrap(); + assert_eq!(response, invalid_version_reply(), "{message}"); + assert!(s.tools().log.is_empty(), "{message}"); + assert!(!s.is_initialized(), "{message}"); + } +} + +/// The stdio entry point validates every envelope and still leaves valid notifications unanswered. +#[test] +fn stdio_refuses_invalid_jsonrpc_versions() { + let messages = malformed_version_messages(); + let (mut s, replies) = serve(&messages); + assert_eq!(replies, vec![invalid_version_reply(); messages.len()]); + assert!(s.tools().log.is_empty()); + assert!(!s.is_initialized()); + assert_eq!(reply(&mut s, &json!({"jsonrpc": "2.0", "method": "notifications/initialized"})), None); + assert!(s.is_initialized()); +} + +/// Batch dispatch uses the same validation while continuing to answer valid requests. +#[test] +fn batches_refuse_invalid_jsonrpc_versions() { + let mut messages = malformed_version_messages(); + let mut expected = vec![invalid_version_reply(); messages.len()]; + messages.push(ping(9)); + expected.push(json!({"jsonrpc": "2.0", "id": 9, "result": {}})); + let mut s = Server::new(info(), Echo::default()); + assert_eq!(reply(&mut s, &Value::Array(messages)), Some(Value::Array(expected))); + assert!(s.tools().log.is_empty()); + assert!(!s.is_initialized()); +} + /// A registered tool is listed and called over the stdio transport, with no engine behind it. #[test] fn a_registered_tool_is_served_over_stdio() { diff --git a/crates/menu/src/driver.rs b/crates/menu/src/driver.rs index 2d2c0c347..3c79dc831 100644 --- a/crates/menu/src/driver.rs +++ b/crates/menu/src/driver.rs @@ -5,6 +5,7 @@ use std::collections::HashSet; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use craft_keymap::{Chord, CommandRef, Key, Mods}; +use craft_ui::contract::MemoProps; use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost}; use crate::layout::{Clash, Layout}; @@ -45,8 +46,9 @@ pub enum ClipboardKeys { Raw, } -/// What may run from the menus this frame, set by the app. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +/// What may run from the menus this frame, set by the app. As props of the runtime's command gate, every flag feeds +/// the key. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, MemoProps)] #[non_exhaustive] pub struct Gate { /// A modal dialog is open. diff --git a/crates/menu/src/modal.rs b/crates/menu/src/modal.rs index a633b5ab4..821118fcb 100644 --- a/crates/menu/src/modal.rs +++ b/crates/menu/src/modal.rs @@ -12,6 +12,7 @@ use std::fmt; use std::sync::Arc; use craft_keymap::CommandRef; +use craft_ui::contract::{MemoKey, MemoProps}; use crate::driver::Gate; use crate::model::{Builtin, Item}; @@ -49,7 +50,8 @@ pub struct ModalRules { /// run. `None`: no pending operation. pub pending: Option, /// The caller's count of rule changes. A rule holds a closure and cannot be compared, so the - /// caller says when the rules changed; the menu skips the resync while it stays the same. + /// caller says when the rules changed; the menu skips the resync, and the runtime's command gate keeps its answers, + /// while it stays the same. pub revision: u64, } @@ -86,6 +88,18 @@ impl ModalRules { } } +/// As props of the runtime's command gate: the plain fields and [`ModalRules::revision`], which stands for the +/// [`ModalRules::pending`] closure. The derive cannot take the closure, and the revision is the caller's count of rule +/// changes, so equal keys mean equal rules as long as the caller moves it with every change. +impl MemoProps for ModalRules { + fn key(&self, key: &mut MemoKey) { + let ModalRules { in_dialogs, workspace, pending: _, revision } = self; + in_dialogs.key(key); + workspace.key(key); + revision.key(key); + } +} + impl fmt::Debug for ModalRules { // new: `PendingRule` is a closure; print whether one is set. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index ef860114f..6ba794aae 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-mesh" -description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX and 3MF readers, bounded on hostile input" +description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX, 3MF, COLLADA and Alembic readers, bounded on hostile input" version.workspace = true edition.workspace = true license.workspace = true @@ -18,6 +18,8 @@ ply = [] gltf = ["dep:serde_json"] fbx = ["dep:miniz_oxide", "dep:craft-zip"] threemf = ["dep:craft-opc", "dep:craft-xml"] +dae = ["dep:craft-xml"] +abc = [] [dependencies] serde_json = { workspace = true, optional = true } diff --git a/crates/mesh/README.md b/crates/mesh/README.md index df32e7a59..c8d335f44 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -11,8 +11,10 @@ a `Scene` into bytes. One Cargo feature per format, all on by default. | `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` | | `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` | | `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` | +| `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` | +| `abc` | Alembic (`.abc`), Ogawa container | yes | no | none | -USD, Alembic and COLLADA are not here yet. +USD is not here yet. ## The neutral model diff --git a/crates/mesh/src/abc.rs b/crates/mesh/src/abc.rs new file mode 100644 index 000000000..b54374d06 --- /dev/null +++ b/crates/mesh/src/abc.rs @@ -0,0 +1,709 @@ +//! Alembic (`.abc`), read: the Ogawa container, `AbcGeom_Xform` hierarchy (matrix, translate, +//! rotate, scale ops; `.inherits`), `AbcGeom_PolyMesh` at its first sample (positions `P`, +//! polygons `.faceIndices` / `.faceCounts` turned counter-clockwise from Alembic's clockwise +//! winding, normals `N` and UVs `uv` at any geometry scope, indexed or not), and +//! `AbcGeom_FaceSet` children as materials. +//! +//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. HDF5-based +//! Alembic files are refused with [`Error::Unsupported`]. + +use std::collections::HashMap; + +use crate::{Corner, Error, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Result, Scene, malformed, mat_mul, too_large}; + +const KIND: &str = "Alembic"; +const OGAWA_MAGIC: &[u8] = b"Ogawa"; +const HDF5_MAGIC: &[u8] = b"\x89HDF\r\n\x1a\n"; +const DATA_BIT: u64 = 1 << 63; +const KEY_BYTES: usize = 16; +const OBJECT_HASH_BYTES: usize = 32; +const MAX_INDEXED_META: usize = 255; + +/// Read an Alembic (`.abc` Ogawa) file into a [`Scene`]. +pub fn read(bytes: &[u8], limits: &Limits) -> Result { + if bytes.starts_with(HDF5_MAGIC) { + return Err(Error::Unsupported("HDF5-based Alembic (re-export the file as Alembic Ogawa, the default since Alembic 1.5)".into())); + } + if !bytes.starts_with(OGAWA_MAGIC) || bytes.len() < 16 { + return Err(malformed(KIND, "not an Alembic Ogawa file")); + } + let mut o = Ogawa { b: bytes, budget: limits.max_data_bytes, max_budget: limits.max_data_bytes, indexed_meta: vec![String::new()] }; + let root_ref = o.u64_at(8)?; + let root = o.group(root_ref)?; + let is_data = |i: usize| root.get(i).is_some_and(|r| r & DATA_BIT != 0); + if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) { + return Err(malformed(KIND, "the archive group does not have the Alembic layout")); + } + let block = o.data(root[5])?; + read_indexed_meta(block, &mut o.indexed_meta)?; + + let mut walk = Walk { o, limits, scene: Scene::default(), materials: HashMap::new(), visits: 0, triangles: 0, parts: 0 }; + walk.object(root[2], None, "", 0)?; + Ok(walk.scene) +} + +struct Ogawa<'a> { + b: &'a [u8], + budget: usize, + max_budget: usize, + indexed_meta: Vec, +} + +#[derive(Clone, Copy, PartialEq)] +enum PropKind { + Compound, + Scalar, + Array, +} + +struct Prop { + name: String, + meta: String, + kind: PropKind, + pod: u32, + extent: usize, + group: u64, +} + +fn meta_get<'m>(meta: &'m str, key: &str) -> Option<&'m str> { + meta.split(';').filter_map(|kv| kv.split_once('=')).find(|(k, _)| *k == key).map(|(_, v)| v) +} + +struct Cursor<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "header block ends early"))?; + self.pos += n; + Ok(s) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or(0)) + } + + fn u32(&mut self) -> Result { + let s = self.take(4)?; + Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + + fn hinted(&mut self, hint: u32) -> Result { + Ok(match hint { + 0 => self.u8()? as usize, + 1 => { + let s = self.take(2)?; + u16::from_le_bytes([s[0], s[1]]) as usize + } + 2 => self.u32()? as usize, + _ => return Err(malformed(KIND, format!("bad size hint {hint}"))), + }) + } + + fn string(&mut self, n: usize) -> Result { + Ok(String::from_utf8_lossy(self.take(n)?).into_owned()) + } +} + +fn f16_to_f64(bits: u16) -> f64 { + let sign = if bits & 0x8000 != 0 { -1.0_f64 } else { 1.0_f64 }; + let exp = (bits >> 10) & 0x1f; + let mant = bits & 0x03ff; + match exp { + 0 => sign * (f64::from(mant) * 2.0_f64.powi(-24)), + 31 => { + if mant == 0 { + sign * f64::INFINITY + } else { + f64::NAN + } + } + _ => sign * ((1.0 + f64::from(mant) / 1024.0) * 2.0_f64.powi(i32::from(exp) - 15)), + } +} + +impl<'a> Ogawa<'a> { + fn charge(&mut self, bytes: usize) -> Result<()> { + self.budget = self.budget.checked_sub(bytes).ok_or_else(|| too_large(KIND, format!("decodes to more than {} bytes", self.max_budget)))?; + Ok(()) + } + + fn u64_at(&self, pos: u64) -> Result { + let p = usize::try_from(pos).map_err(|_| malformed(KIND, "offset out of range"))?; + let s = + p.checked_add(8).and_then(|e| self.b.get(p..e)).ok_or_else(|| malformed(KIND, format!("offset {pos} is past the end of the file")))?; + let mut a = [0u8; 8]; + a.copy_from_slice(s); + Ok(u64::from_le_bytes(a)) + } + + fn group(&mut self, r: u64) -> Result> { + if r & DATA_BIT != 0 { + return Err(malformed(KIND, "expected a group, found a data block")); + } + if r == 0 { + return Ok(Vec::new()); + } + let n = self.u64_at(r)?; + let room = (self.b.len() as u64).saturating_sub(r.saturating_add(8)) / 8; + if n > room { + return Err(malformed(KIND, format!("group at {r} claims {n} children"))); + } + self.charge(n as usize * 8)?; + (0..n).map(|i| self.u64_at(r + 8 + 8 * i)).collect() + } + + fn data(&self, r: u64) -> Result<&'a [u8]> { + if r & DATA_BIT == 0 { + return Err(malformed(KIND, "expected a data block, found a group")); + } + let off = r & !DATA_BIT; + if off == 0 { + return Ok(&[]); + } + let size = self.u64_at(off)?; + let start = usize::try_from(off + 8).map_err(|_| malformed(KIND, "offset out of range"))?; + usize::try_from(size) + .ok() + .and_then(|s| start.checked_add(s)) + .and_then(|end| self.b.get(start..end)) + .ok_or_else(|| malformed(KIND, format!("data block at {off} ({size} bytes) overruns the file"))) + } + + fn meta_at(&self, index: u8) -> String { + self.indexed_meta.get(index as usize).cloned().unwrap_or_default() + } + + fn compound(&mut self, r: u64) -> Result> { + let children = self.group(r)?; + let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) }; + let block = self.data(last)?; + self.charge(block.len())?; + let mut c = Cursor { b: block, pos: 0 }; + let mut out = Vec::new(); + while c.pos < block.len() { + let info = c.u32()?; + let hint = (info & 0xc) >> 2; + let kind = match info & 0x3 { + 0 => PropKind::Compound, + 1 => PropKind::Scalar, + _ => PropKind::Array, + }; + let (pod, extent) = ((info & 0xf0) >> 4, ((info & 0xff000) >> 12) as usize); + if kind != PropKind::Compound { + let _samples = c.hinted(hint)?; + if info & 0x200 != 0 { + c.hinted(hint)?; + c.hinted(hint)?; + } + if info & 0x100 != 0 { + c.hinted(hint)?; + } + } + let name_len = c.hinted(hint)?; + let name = c.string(name_len)?; + let meta_index = ((info & 0xff0_0000) >> 20) as u8; + let meta = if meta_index == 0xff { + let n = c.hinted(hint)?; + c.string(n)? + } else { + self.meta_at(meta_index) + }; + let group = children.get(out.len()).copied().ok_or_else(|| malformed(KIND, format!("property \"{name}\" has no group")))?; + out.push(Prop { name, meta, kind, pod, extent, group }); + } + Ok(out) + } + + fn values(&mut self, property: &Prop) -> Result> { + let samples = self.group(property.group)?; + let Some(&first) = samples.first() else { return Ok(Vec::new()) }; + + let raw = self.data(first)?; + let raw = if raw.is_empty() { + raw + } else { + raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))? + }; + + let value_bytes = match property.pod { + 0..=2 => 1, + 3 | 4 | 9 => 2, + 5 | 6 | 10 => 4, + 7 | 8 | 11 => 8, + other => return Err(Error::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), + }; + self.charge((raw.len() / value_bytes).saturating_mul(8))?; + + Ok(match property.pod { + 0 | 1 => raw.iter().map(|v| *v as f64).collect(), + 2 => raw.iter().map(|v| *v as i8 as f64).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 9 => raw.as_chunks::<2>().0.iter().map(|c| f16_to_f64(u16::from_le_bytes(*c))).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), + }) + } + + fn object_headers(&mut self, children: &[u64]) -> Result> { + let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) }; + let block = self.data(last)?; + self.charge(block.len())?; + let body = block.get(..block.len().saturating_sub(OBJECT_HASH_BYTES)).unwrap_or_default(); + let mut c = Cursor { b: body, pos: 0 }; + let mut out = Vec::new(); + while c.pos < body.len() { + let n = c.u32()? as usize; + let name = c.string(n)?; + let index = c.u8()?; + let meta = if index == 0xff { + let n = c.u32()? as usize; + c.string(n)? + } else { + self.meta_at(index) + }; + out.push((name, meta)); + } + Ok(out) + } +} + +fn read_indexed_meta(block: &[u8], out: &mut Vec) -> Result<()> { + let mut c = Cursor { b: block, pos: 0 }; + while c.pos < block.len() && out.len() < MAX_INDEXED_META { + let n = c.u8()? as usize; + out.push(c.string(n)?); + } + Ok(()) +} + +#[derive(Clone, Copy)] +enum Scope { + Constant, + Uniform, + Vertex, + FaceVarying, +} + +struct Param { + vals: Vec, + indices: Option>, + scope: Scope, +} + +impl Param { + fn get(&self, k: usize, p: usize, f: usize) -> Option<[f64; W]> { + let i = match self.scope { + Scope::Constant => 0, + Scope::Uniform => f, + Scope::Vertex => p, + Scope::FaceVarying => k, + }; + let i = match &self.indices { + Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, + None => i, + }; + let start = i.checked_mul(W)?; + self.vals.get(start..start.checked_add(W)?)?.try_into().ok() + } +} + +fn find<'p>(props: &'p [Prop], name: &str) -> Option<&'p Prop> { + props.iter().find(|p| p.name == name) +} + +fn schema_compound<'p>(props: &'p [Prop], schema: &str, name: &str) -> Option<&'p Prop> { + let compounds = || props.iter().filter(|p| p.kind == PropKind::Compound); + compounds().find(|p| meta_get(&p.meta, "schema") == Some(schema)).or_else(|| compounds().find(|p| p.name == name)) +} + +struct Walk<'a> { + o: Ogawa<'a>, + limits: &'a Limits, + scene: Scene, + materials: HashMap, + visits: usize, + triangles: usize, + parts: usize, +} + +impl Walk<'_> { + fn warn(&mut self, msg: String) { + if !self.scene.warnings.contains(&msg) { + self.scene.warnings.push(msg); + } + } + + fn push_node(&mut self, node: Node, parent: Option) -> Result { + if self.scene.nodes.len() >= self.limits.max_nodes { + return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes))); + } + let idx = self.scene.nodes.len(); + self.scene.nodes.push(node); + match parent { + Some(p) => self.scene.nodes[p].children.push(idx), + None => self.scene.roots.push(idx), + } + Ok(idx) + } + + fn intern_material(&mut self, name: &str) -> Result { + if let Some(&idx) = self.materials.get(name) { + return Ok(idx); + } + if self.scene.materials.len() >= self.limits.max_materials { + return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials))); + } + let idx = self.scene.materials.len(); + self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() }); + self.materials.insert(name.to_owned(), idx); + Ok(idx) + } + + fn object(&mut self, r: u64, parent_node: Option, xform_name: &str, depth: usize) -> Result<()> { + self.visits += 1; + if depth > self.limits.max_depth || self.visits > self.limits.max_nodes { + return Err(malformed(KIND, "objects are nested too deeply or shared too often")); + } + let children = self.o.group(r)?; + let headers = self.o.object_headers(&children)?; + for (i, (name, meta)) in headers.iter().enumerate() { + let group = children + .get(i + 1) + .copied() + .filter(|g| g & DATA_BIT == 0) + .ok_or_else(|| malformed(KIND, format!("object \"{name}\" has no group")))?; + let schema = meta_get(meta, "schema").unwrap_or_default(); + let kids = self.o.group(group)?; + let props = match kids.first() { + Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?, + _ => Vec::new(), + }; + + let mut next_parent = parent_node; + if schema.starts_with("AbcGeom_Xform") { + if let Some(xf) = schema_compound(&props, schema, ".xform") { + let (local, inherits) = self.xform(xf.group)?; + let attach_to = if inherits { parent_node } else { None }; + let node_idx = self.push_node(Node { name: name.clone(), transform: local, ..Node::default() }, attach_to)?; + next_parent = Some(node_idx); + } + } else if schema.starts_with("AbcGeom_PolyMesh") + && let Some(geom) = schema_compound(&props, schema, ".geom") + { + let part_name = if xform_name.is_empty() { name.clone() } else { xform_name.to_string() }; + let sets = self.face_sets(&kids)?; + let mesh = self.mesh(geom.group, &part_name, &sets)?; + if self.scene.meshes.len() >= self.limits.max_meshes { + return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes))); + } + let mesh_idx = self.scene.meshes.len(); + self.scene.meshes.push(mesh); + let node_idx = self.push_node(Node { name: part_name, mesh: Some(mesh_idx), ..Node::default() }, parent_node)?; + next_parent = Some(node_idx); + } + + if !schema.starts_with("AbcGeom_FaceSet") { + let owner = if schema.starts_with("AbcGeom_Xform") { name.as_str() } else { "" }; + self.object(group, next_parent, owner, depth + 1)?; + } + } + Ok(()) + } + + fn xform(&mut self, r: u64) -> Result<(Mat4, bool)> { + let props = self.o.compound(r)?; + let ops = match find(&props, ".ops") { + Some(p) => self.o.values(p)?, + None => Vec::new(), + }; + let vals = match find(&props, ".vals") { + Some(p) => self.o.values(p)?, + None => Vec::new(), + }; + let inherits = match find(&props, ".inherits") { + Some(p) => self.o.values(p)?.first().is_none_or(|v| *v != 0.0), + None => true, + }; + let mut m = IDENTITY; + let mut ch = 0usize; + for op in ops { + let kind = (op as u32) >> 4; + let n = match kind { + 0 | 1 => 3, + 2 => 4, + 3 => 16, + 4..=6 => 1, + _ => return Err(malformed(KIND, format!("unknown xform operation {kind}"))), + }; + let Some(v) = vals.get(ch..ch + n) else { return Err(malformed(KIND, "xform has fewer values than its operations need")) }; + ch += n; + let op_m = match kind { + 0 => [v[0], 0.0, 0.0, 0.0, 0.0, v[1], 0.0, 0.0, 0.0, 0.0, v[2], 0.0, 0.0, 0.0, 0.0, 1.0], + 1 => [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, v[0], v[1], v[2], 1.0], + 2 => axis_angle_matrix([v[0], v[1], v[2]], v[3].to_radians()), + 3 => { + let mut a = [0.0; 16]; + a.copy_from_slice(v); + a + } + 4 => rot_x(v[0].to_radians()), + 5 => rot_y(v[0].to_radians()), + _ => rot_z(v[0].to_radians()), + }; + m = mat_mul(&m, &op_m); + } + if !m.iter().all(|x| x.is_finite()) { + return Err(malformed(KIND, "xform has non-finite values")); + } + Ok((m, inherits)) + } + + fn face_sets(&mut self, kids: &[u64]) -> Result)>> { + let headers = self.o.object_headers(kids)?; + let mut out = Vec::new(); + for (i, (name, meta)) in headers.iter().enumerate() { + let schema = meta_get(meta, "schema").unwrap_or_default(); + if !schema.starts_with("AbcGeom_FaceSet") { + continue; + } + let Some(&g) = kids.get(i + 1).filter(|g| **g & DATA_BIT == 0) else { continue }; + let props = match self.o.group(g)?.first() { + Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?, + _ => continue, + }; + let Some(fs) = schema_compound(&props, schema, ".faceset") else { continue }; + let inner = self.o.compound(fs.group)?; + if let Some(faces) = find(&inner, ".faces") { + out.push((name.clone(), self.o.values(faces)?)); + } + } + Ok(out) + } + + fn param(&mut self, props: &[Prop], name: &str, counts: [usize; 3]) -> Result> { + let Some(p) = find(props, name) else { return Ok(None) }; + let (vals, indices) = match p.kind { + PropKind::Array => (self.o.values(p)?, None), + PropKind::Compound => { + let inner = self.o.compound(p.group)?; + let Some(v) = find(&inner, ".vals") else { return Ok(None) }; + let vals = self.o.values(v)?; + let indices = match find(&inner, ".indices") { + Some(ix) => Some(self.o.values(ix)?), + None => None, + }; + (vals, indices) + } + PropKind::Scalar => return Ok(None), + }; + let width = p.extent.max(1); + let items = indices.as_ref().map_or(vals.len() / width, Vec::len); + let [points, faces, corners] = counts; + let scope = match meta_get(&p.meta, "geoScope") { + Some("con") => Scope::Constant, + Some("uni") => Scope::Uniform, + Some("vtx" | "var") => Scope::Vertex, + Some("fvr") => Scope::FaceVarying, + _ if items == corners => Scope::FaceVarying, + _ if items == points => Scope::Vertex, + _ if items == faces => Scope::Uniform, + _ => Scope::Constant, + }; + Ok(Some(Param { vals, indices, scope })) + } + + fn mesh(&mut self, r: u64, name: &str, sets: &[(String, Vec)]) -> Result { + let properties = self.o.compound(r)?; + let get = |o: &mut Ogawa, prop_name: &str| -> Result> { + match find(&properties, prop_name) { + Some(p) => o.values(p), + None => Err(malformed(KIND, format!("PolyMesh has no {prop_name}"))), + } + }; + + let p = get(&mut self.o, "P")?; + let indices = get(&mut self.o, ".faceIndices")?; + let counts = get(&mut self.o, ".faceCounts")?; + let num_points = p.len() / 3; + if num_points > self.limits.max_vertices { + return Err(too_large(KIND, format!("more than {} vertices", self.limits.max_vertices))); + } + let positions: Vec<[f64; 3]> = p.as_chunks::<3>().0.to_vec(); + let n = [positions.len(), counts.len(), indices.len()]; + let normals_param = self.param(&properties, "N", n)?; + let uvs_param = self.param(&properties, "uv", n)?; + + let mut face_material = vec![None::; counts.len()]; + for (s, (_, faces)) in sets.iter().enumerate() { + for f in faces { + if let Some(m) = face_material.get_mut(*f as usize).filter(|m| m.is_none() && *f >= 0.0) { + *m = Some(s); + } + } + } + + let mut mesh = Mesh { name: name.to_string(), positions, ..Mesh::default() }; + let mut norm_ids: HashMap<[u64; 3], u32> = HashMap::new(); + let mut uv_ids: HashMap<[u32; 2], u32> = HashMap::new(); + let mut uv_pool: Vec<[f32; 2]> = Vec::new(); + let mut parts_by_mat: HashMap, Part> = HashMap::new(); + let mut part_order: Vec> = Vec::new(); + + let (mut k, mut face_corners, mut bad_uvs) = (0usize, Vec::new(), 0usize); + for (f, &count) in counts.iter().enumerate() { + let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len()); + let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?; + let face_len = end - k; + if face_len > self.limits.max_face_corners { + return Err(too_large(KIND, format!("face {f} has more than {} corners", self.limits.max_face_corners))); + } + if face_len >= 3 { + self.triangles = self.triangles.saturating_add(face_len - 2); + if self.triangles > self.limits.max_triangles { + return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles))); + } + face_corners.clear(); + for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) { + if point_index < 0.0 || (point_index as usize) >= mesh.positions.len() { + return Err(malformed(KIND, format!("point index {point_index} out of range"))); + } + let pt = point_index as usize; + let norm_idx = match normals_param.as_ref().and_then(|l| l.get::<3>(corner_index, pt, f)) { + Some(norm) => intern_norm(&mut mesh.normals, &mut norm_ids, norm, self.limits.max_vertices)?, + None => crate::NONE, + }; + let uv_idx = match &uvs_param { + Some(l) => { + let uv = match l.get::<2>(corner_index, pt, f) { + Some([u, v]) => [u as f32, 1.0 - v as f32], + None => { + bad_uvs += 1; + [0.0, 0.0] + } + }; + intern_uv(&mut uv_pool, &mut uv_ids, uv, self.limits.max_vertices)? + } + None => crate::NONE, + }; + face_corners.push(Corner { position: pt as u32, normal: norm_idx, uv: uv_idx }); + } + // Alembic winds polygons clockwise; reverse to counter-clockwise. + face_corners.reverse(); + + let mat_idx = match face_material.get(f).copied().flatten().and_then(|s| sets.get(s)) { + Some((mat_name, _)) => Some(self.intern_material(mat_name)?), + None => None, + }; + let part = match parts_by_mat.entry(mat_idx) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + self.parts += 1; + if self.parts > self.limits.max_parts { + return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts))); + } + part_order.push(mat_idx); + e.insert(Part { material: mat_idx, ..Part::default() }) + } + }; + part.corners.extend_from_slice(&face_corners); + part.face_sizes.push(face_corners.len() as u32); + } + k = end; + } + + for mat_idx in part_order { + if let Some(mut part) = parts_by_mat.remove(&mat_idx) { + if part.face_sizes.iter().all(|&s| s == 3) { + part.face_sizes.clear(); + } + mesh.parts.push(part); + } + } + if !uv_pool.is_empty() { + mesh.uv_sets.push(uv_pool); + } + if bad_uvs > 0 { + self.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)")); + } + Ok(mesh) + } +} + +fn intern_norm(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize) -> Result { + let key = val.map(f64::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} normals"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many normals"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result { + let key = val.map(f32::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} UVs"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Mat4 { + let len = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt(); + if !len.is_finite() || len == 0.0 { + return IDENTITY; + } + let [x, y, z] = axis.map(|v| v / len); + let (s, c) = angle.sin_cos(); + let t = 1.0 - c; + [ + t * x * x + c, + t * x * y + s * z, + t * x * z - s * y, + 0.0, + t * x * y - s * z, + t * y * y + c, + t * y * z + s * x, + 0.0, + t * x * z + s * y, + t * y * z - s * x, + t * z * z + c, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ] +} + +fn rot_x(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0] +} + +fn rot_y(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0] +} + +fn rot_z(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] +} diff --git a/crates/mesh/src/dae.rs b/crates/mesh/src/dae.rs new file mode 100644 index 000000000..b5a06c612 --- /dev/null +++ b/crates/mesh/src/dae.rs @@ -0,0 +1,583 @@ +//! COLLADA (`.dae`), read: `triangles`, `polylist` and `polygons` with `VERTEX` / `NORMAL` / +//! `TEXCOORD` inputs, materials bound through `instance_geometry` and `instance_controller`, the +//! visual scene's node hierarchy and transforms (`matrix`, `translate`, `rotate`, `scale`, +//! `lookat`), `instance_node`, `instance_camera`, and the asset's unit (`meter`) and `up_axis`. +//! +//! [`read_document`] returns the [`Scene`] in the file's own axes and units alongside +//! [`Document::meter`] and [`Document::up_axis`] (and [`Document::global_transform`] to convert to +//! Y-up metres). [`read`] returns the [`Scene`] directly. +//! +//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. + +use std::collections::HashMap; +use std::rc::Rc; + +use craft_xml::{El, Options, UnknownEntity}; + +use crate::{Camera, Corner, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Projection, Result, Scene, malformed, mat_mul, too_large}; + +const KIND: &str = "COLLADA"; +const MAX_XML_DEPTH: usize = 256; +const MAX_XML_NODES: usize = 2_000_000; + +/// Up axis of a COLLADA ``. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum UpAxis { + #[default] + YUp, + ZUp, + XUp, +} + +impl UpAxis { + /// Rotation matrix that turns this axis into +Y up. + pub fn to_y_up(self) -> Mat4 { + match self { + UpAxis::YUp => IDENTITY, + UpAxis::ZUp => [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], + UpAxis::XUp => [0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0], + } + } +} + +/// A COLLADA document: the scene in the file's own axes and units, plus its `` scale and +/// up axis. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Document { + pub scene: Scene, + /// Metres per file unit (default `1.0`). + pub meter: f64, + pub up_axis: UpAxis, +} + +impl Document { + /// Transform from the file's axes and units to Y-up metres. + pub fn global_transform(&self) -> Mat4 { + let scale = [self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, 1.0]; + mat_mul(&self.up_axis.to_y_up(), &scale) + } +} + +/// Read a COLLADA file into a [`Scene`] (in the file's own axes and units). +pub fn read(bytes: &[u8], limits: &Limits) -> Result { + Ok(read_document(bytes, limits)?.scene) +} + +/// Read a COLLADA file into a [`Document`]. +pub fn read_document(bytes: &[u8], limits: &Limits) -> Result { + let mut opts = Options::local(); + opts.unknown_entity = UnknownEntity::Literal; + opts.strict_end_tags = true; + opts.limits.max_input = limits.max_data_bytes; + opts.limits.max_depth = MAX_XML_DEPTH; + opts.limits.max_nodes = MAX_XML_NODES; + let root = opts.parse(bytes).map_err(|e| if e.is_limit() { too_large(KIND, e) } else { malformed(KIND, e) })?; + if root.name != "COLLADA" { + return Err(malformed(KIND, "not a COLLADA document")); + } + + let mut ids: HashMap<&str, &El> = HashMap::new(); + let mut stack = vec![&root]; + while let Some(el) = stack.pop() { + if let Some(id) = el.attr("id") { + ids.entry(id).or_insert(el); + } + stack.extend(el.elements()); + } + + let asset = root.child("asset"); + let meter = asset + .and_then(|a| a.child("unit")) + .and_then(|u| u.attr("meter")) + .and_then(|m| m.trim().parse::().ok()) + .filter(|m| m.is_finite() && *m > 0.0) + .unwrap_or(1.0); + let up_axis = match asset.and_then(|a| a.child("up_axis")).map(|u| u.text().trim().to_owned()).as_deref() { + Some("Z_UP") => UpAxis::ZUp, + Some("X_UP") => UpAxis::XUp, + _ => UpAxis::YUp, + }; + + let mut reader = + Reader { ids, sources: HashMap::new(), limits, scene: Scene::default(), materials: HashMap::new(), mesh_cache: HashMap::new(), triangles: 0 }; + + let visual_scene = root + .child("scene") + .and_then(|s| s.child("instance_visual_scene")) + .and_then(|i| reader.get(i.attr("url"))) + .or_else(|| root.child("library_visual_scenes").and_then(|l| l.child("visual_scene"))); + + if let Some(vs) = visual_scene { + for n in vs.children("node") { + let idx = reader.read_node(n, 0)?; + reader.scene.roots.push(idx); + } + } else { + for geom in root.children("library_geometries").flat_map(|l| l.children("geometry")) { + let mesh_idx = reader.get_or_build_mesh(geom, &[])?; + let name = reader.scene.meshes[mesh_idx].name.clone(); + let node_idx = reader.push_node(Node { name, mesh: Some(mesh_idx), ..Node::default() })?; + reader.scene.roots.push(node_idx); + } + } + + Ok(Document { scene: reader.scene, meter, up_axis }) +} + +struct Source { + data: Vec, + stride: usize, + offset: usize, +} + +impl Source { + fn get(&self, i: u32) -> Option<[f64; W]> { + let start = (i as usize).checked_mul(self.stride)?.checked_add(self.offset)?; + self.data.get(start..start.checked_add(W)?)?.try_into().ok() + } +} + +struct Input { + offset: usize, + source: Rc, +} + +struct Reader<'a> { + ids: HashMap<&'a str, &'a El>, + sources: HashMap<&'a str, Rc>, + limits: &'a Limits, + scene: Scene, + materials: HashMap, + /// Keyed by `(geometry element pointer, sorted (symbol, material_name) bindings)`. + mesh_cache: HashMap<(usize, Vec<(String, String)>), usize>, + triangles: usize, +} + +impl<'a> Reader<'a> { + fn get(&self, url: Option<&str>) -> Option<&'a El> { + url.and_then(|u| u.strip_prefix('#')).and_then(|id| self.ids.get(id)).copied() + } + + fn warn(&mut self, msg: String) { + if !self.scene.warnings.contains(&msg) { + self.scene.warnings.push(msg); + } + } + + fn push_node(&mut self, node: Node) -> Result { + if self.scene.nodes.len() >= self.limits.max_nodes { + return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes))); + } + let idx = self.scene.nodes.len(); + self.scene.nodes.push(node); + Ok(idx) + } + + fn intern_material(&mut self, name: &str) -> Result { + if let Some(&idx) = self.materials.get(name) { + return Ok(idx); + } + if self.scene.materials.len() >= self.limits.max_materials { + return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials))); + } + let idx = self.scene.materials.len(); + self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() }); + self.materials.insert(name.to_owned(), idx); + Ok(idx) + } + + fn source(&mut self, url: Option<&str>) -> Result> { + let el = self.get(url).ok_or_else(|| malformed(KIND, format!("missing source {}", url.unwrap_or("(none)"))))?; + let id = el.attr("id").unwrap_or_default(); + if !id.is_empty() + && let Some(s) = self.sources.get(id) + { + return Ok(s.clone()); + } + let acc = el.child("technique_common").and_then(|t| t.child("accessor")); + let array = acc.and_then(|a| self.get(a.attr("source"))).or_else(|| el.child("float_array")); + let array = array.ok_or_else(|| malformed(KIND, format!("source \"{id}\" has no float_array")))?; + let num = |k: &str, default: usize| acc.and_then(|a| a.attr(k)).and_then(|v| v.parse().ok()).unwrap_or(default); + let data = parse_floats(array)?; + if data.len() / 3 > self.limits.max_vertices { + return Err(too_large(KIND, format!("source has more than {} vertices", self.limits.max_vertices))); + } + let s = Rc::new(Source { data, stride: num("stride", 1).max(1), offset: num("offset", 0) }); + if !id.is_empty() { + self.sources.insert(id, s.clone()); + } + Ok(s) + } + + fn read_node(&mut self, el: &'a El, depth: usize) -> Result { + if depth > self.limits.max_depth { + return Err(too_large(KIND, format!("node hierarchy is deeper than {}", self.limits.max_depth))); + } + let name = el.attr("name").or_else(|| el.attr("id")).unwrap_or_default().to_string(); + let transform = node_transform(el)?; + let mut node = Node { name: name.clone(), transform, ..Node::default() }; + + for inst in el.elements() { + if inst.name == "instance_camera" { + if node.camera.is_none() + && let Some(cam_el) = self.get(inst.attr("url")) + && let Some(cam) = parse_camera(cam_el, &name) + && self.scene.cameras.len() < self.limits.max_extras + { + let cam_idx = self.scene.cameras.len(); + self.scene.cameras.push(cam); + node.camera = Some(cam_idx); + } + continue; + } + let (geom, bind_shape) = match inst.name.as_str() { + "instance_geometry" => (self.get(inst.attr("url")), IDENTITY), + "instance_controller" => { + let skin = self.get(inst.attr("url")).and_then(|c| c.child("skin")); + let bind = skin.and_then(|s| s.child("bind_shape_matrix")).map(parse_floats).transpose()?.and_then(|v| row_major_matrix(&v)); + (skin.and_then(|s| self.get(s.attr("source"))), bind.unwrap_or(IDENTITY)) + } + _ => continue, + }; + let Some(geom) = geom else { + self.warn("an instanced geometry is missing from the file".into()); + continue; + }; + let bind = self.bindings(inst); + let mesh_idx = self.get_or_build_mesh(geom, &bind)?; + if node.mesh.is_none() && bind_shape == IDENTITY { + node.mesh = Some(mesh_idx); + } else { + let child = self.push_node(Node { name: name.clone(), transform: bind_shape, mesh: Some(mesh_idx), ..Node::default() })?; + node.children.push(child); + } + } + + for child_el in el.children("node") { + let child = self.read_node(child_el, depth + 1)?; + node.children.push(child); + } + for inst_node in el.children("instance_node") { + if let Some(target) = self.get(inst_node.attr("url")) { + let child = self.read_node(target, depth + 1)?; + node.children.push(child); + } + } + + self.push_node(node) + } + + fn bindings(&self, inst: &El) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = inst + .child("bind_material") + .and_then(|b| b.child("technique_common")) + .into_iter() + .flat_map(|t| t.children("instance_material")) + .filter_map(|im| { + let symbol = im.attr("symbol")?; + let mat = self.get(im.attr("target")); + let name = mat.and_then(|m| m.attr("name").or_else(|| m.attr("id"))).unwrap_or(symbol); + Some((symbol.to_string(), name.to_string())) + }) + .collect(); + out.sort(); + out + } + + fn get_or_build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result { + let key = ((geom as *const El) as usize, bind.to_vec()); + if let Some(&idx) = self.mesh_cache.get(&key) { + return Ok(idx); + } + if self.scene.meshes.len() >= self.limits.max_meshes { + return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes))); + } + let mesh = self.build_mesh(geom, bind)?; + let idx = self.scene.meshes.len(); + self.scene.meshes.push(mesh); + self.mesh_cache.insert(key, idx); + Ok(idx) + } + + fn build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result { + let name = geom.attr("name").or_else(|| geom.attr("id")).unwrap_or_default().to_string(); + let mut mesh = Mesh { name, ..Mesh::default() }; + let Some(mesh_el) = geom.child("mesh") else { return Ok(mesh) }; + + let mut pools = MeshPools::default(); + let mut part_count: usize = self.scene.meshes.iter().map(|m| m.parts.len()).sum(); + + for prim in mesh_el.elements() { + if !matches!(prim.name.as_str(), "triangles" | "polylist" | "polygons") { + if matches!(prim.name.as_str(), "lines" | "linestrips" | "trifans" | "tristrips") { + self.warn(format!("skipped COLLADA <{}> (only triangles and polygons are supported)", prim.name)); + } + continue; + } + let Some(inputs) = self.read_primitive_inputs(prim)? else { + self.warn("skipped COLLADA primitives without positions".into()); + continue; + }; + part_count += 1; + if part_count > self.limits.max_parts { + return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts))); + } + let material = match prim.attr("material") { + Some(sym) => { + let mat_name = bind.binary_search_by(|(k, _)| k.as_str().cmp(sym)).ok().map_or(sym, |i| bind[i].1.as_str()); + Some(self.intern_material(mat_name)?) + } + None => None, + }; + let lists = read_primitive_lists(prim, inputs.stride)?; + let part = self.build_part(material, &inputs, &lists, &mut mesh, &mut pools)?; + if !part.corners.is_empty() { + mesh.parts.push(part); + } + } + if !pools.uvs.is_empty() { + mesh.uv_sets.push(pools.uvs); + } + Ok(mesh) + } + + fn read_primitive_inputs(&mut self, prim: &'a El) -> Result> { + let (mut position, mut normal, mut uv): (Option, Option, Option<(u32, Input)>) = (None, None, None); + let mut stride = 1usize; + for input in prim.children("input") { + let offset: usize = input.attr("offset").and_then(|o| o.parse().ok()).unwrap_or(0); + stride = stride.max(offset.saturating_add(1)); + let nested: Vec<&El> = match input.attr("semantic") { + Some("VERTEX") => self.get(input.attr("source")).map(|v| v.children("input").collect()).unwrap_or_default(), + _ => vec![input], + }; + for i in nested { + let set: u32 = input.attr("set").or_else(|| i.attr("set")).and_then(|s| s.parse().ok()).unwrap_or(0); + match i.attr("semantic") { + Some("POSITION") => position = Some(Input { offset, source: self.source(i.attr("source"))? }), + Some("NORMAL") if normal.is_none() => normal = Some(Input { offset, source: self.source(i.attr("source"))? }), + Some("TEXCOORD") if uv.as_ref().is_none_or(|(s, _)| set < *s) => { + uv = Some((set, Input { offset, source: self.source(i.attr("source"))? })) + } + _ => {} + } + } + } + Ok(position.map(|position| PrimInputs { stride, position, normal, uv: uv.map(|(_, i)| i) })) + } + + fn build_part( + &mut self, + material: Option, + inputs: &PrimInputs, + lists: &[(Vec, Vec)], + mesh: &mut Mesh, + pools: &mut MeshPools, + ) -> Result { + let mut part = Part { material, ..Part::default() }; + let mut all_triangles = true; + for (p, sizes) in lists { + let mut next = 0usize; + for &size in sizes { + if size > self.limits.max_face_corners { + return Err(too_large(KIND, format!("face has more than {} corners", self.limits.max_face_corners))); + } + if size >= 3 { + self.triangles = self.triangles.saturating_add(size - 2); + if self.triangles > self.limits.max_triangles { + return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles))); + } + if size != 3 { + all_triangles = false; + } + for c in next..next.saturating_add(size) { + let idx = + |input: &Input| c.checked_mul(inputs.stride).and_then(|b| b.checked_add(input.offset)).and_then(|k| p.get(k)).copied(); + let pos = idx(&inputs.position) + .and_then(|i| inputs.position.source.get::<3>(i)) + .ok_or_else(|| malformed(KIND, "polygon index out of range"))?; + let pos_idx = intern_f64_3(&mut mesh.positions, &mut pools.pos_ids, pos, self.limits.max_vertices, "positions")?; + let norm_idx = match inputs.normal.as_ref().and_then(|n| idx(n).and_then(|i| n.source.get::<3>(i))) { + Some(n) => intern_f64_3(&mut mesh.normals, &mut pools.norm_ids, n, self.limits.max_vertices, "normals")?, + None => crate::NONE, + }; + let uv_idx = match inputs.uv.as_ref().and_then(|t| idx(t).and_then(|i| t.source.get::<2>(i))) { + Some([u, v]) => intern_uv(&mut pools.uvs, &mut pools.uv_ids, [u as f32, 1.0 - v as f32], self.limits.max_vertices)?, + None => crate::NONE, + }; + part.corners.push(Corner { position: pos_idx, normal: norm_idx, uv: uv_idx }); + } + part.face_sizes.push(size as u32); + } + next = next.saturating_add(size); + } + } + if all_triangles { + part.face_sizes.clear(); + } + Ok(part) + } +} + +#[derive(Default)] +struct MeshPools { + pos_ids: HashMap<[u64; 3], u32>, + norm_ids: HashMap<[u64; 3], u32>, + uv_ids: HashMap<[u32; 2], u32>, + uvs: Vec<[f32; 2]>, +} + +struct PrimInputs { + stride: usize, + position: Input, + normal: Option, + uv: Option, +} + +fn read_primitive_lists(prim: &El, stride: usize) -> Result, Vec)>> { + match prim.name.as_str() { + "polygons" => prim + .children("p") + .map(|p| { + let p = parse_indices(p)?; + let n = p.len() / stride; + Ok((p, vec![n])) + }) + .collect(), + _ => { + let p = prim.child("p").map(parse_indices).transpose()?.unwrap_or_default(); + let sizes = match prim.child("vcount") { + Some(v) if prim.name == "polylist" => parse_indices(v)?.into_iter().map(|c| c as usize).collect(), + _ => vec![3; p.len() / stride / 3], + }; + Ok(vec![(p, sizes)]) + } + } +} + +fn intern_f64_3(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize, what: &str) -> Result { + let key = val.map(f64::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} {what}"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, format!("too many {what}")))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result { + let key = val.map(f32::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} UVs"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn parse_floats(el: &El) -> Result> { + el.text().split_whitespace().map(|w| w.parse::().map_err(|_| malformed(KIND, format!("bad number \"{w}\" in <{}>", el.name)))).collect() +} + +fn parse_indices(el: &El) -> Result> { + el.text().split_whitespace().map(|w| w.parse::().map_err(|_| malformed(KIND, format!("bad index \"{w}\" in <{}>", el.name)))).collect() +} + +fn parse_camera(cam: &El, node_name: &str) -> Option { + let tc = cam.child("optics")?.child("technique_common")?; + let num = |e: &El, k: &str| e.child(k).and_then(|v| v.text().trim().parse::().ok()).filter(|v| v.is_finite() && *v > 0.0); + let name = if node_name.is_empty() { cam.attr("name").or_else(|| cam.attr("id")).unwrap_or_default().to_string() } else { node_name.to_string() }; + if let Some(p) = tc.child("perspective") { + let x_to_y = |x: f64| Some(2.0 * ((x * 0.5).to_radians().tan() / num(p, "aspect_ratio")?).atan().to_degrees()); + let fov_deg = num(p, "yfov").or_else(|| num(p, "xfov").and_then(x_to_y)).or_else(|| num(p, "xfov")).unwrap_or(40.0); + let aspect = num(p, "aspect_ratio"); + let znear = num(p, "znear").unwrap_or(0.1); + let zfar = num(p, "zfar"); + return Some(Camera { name, projection: Projection::Perspective { yfov: fov_deg.to_radians(), aspect, znear, zfar } }); + } + let o = tc.child("orthographic")?; + let aspect = num(o, "aspect_ratio"); + let ymag = num(o, "ymag").or_else(|| Some(num(o, "xmag")? / aspect?)).or_else(|| num(o, "xmag")).unwrap_or(1.0); + let xmag = num(o, "xmag").unwrap_or_else(|| ymag * aspect.unwrap_or(1.0)); + let znear = num(o, "znear").unwrap_or(0.1); + let zfar = num(o, "zfar").unwrap_or(1000.0); + Some(Camera { name, projection: Projection::Orthographic { xmag, ymag, znear, zfar } }) +} + +/// Row-major 4×4 floats to a column-major matrix. +fn row_major_matrix(v: &[f64]) -> Option { + let a: [f64; 16] = v.get(..16)?.try_into().ok()?; + Some([a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15]]) +} + +fn node_transform(node: &El) -> Result { + let mut m = IDENTITY; + for t in node.elements() { + let v = match t.name.as_str() { + "matrix" | "translate" | "rotate" | "scale" | "lookat" => parse_floats(t)?, + _ => continue, + }; + let step = match (t.name.as_str(), v.as_slice()) { + ("matrix", _) => row_major_matrix(&v), + ("translate", [x, y, z, ..]) => Some([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, *x, *y, *z, 1.0]), + ("scale", [x, y, z, ..]) => Some([*x, 0.0, 0.0, 0.0, 0.0, *y, 0.0, 0.0, 0.0, 0.0, *z, 0.0, 0.0, 0.0, 0.0, 1.0]), + ("rotate", [x, y, z, deg, ..]) => axis_angle_matrix([*x, *y, *z], deg.to_radians()), + ("lookat", [ex, ey, ez, ix, iy, iz, ux, uy, uz, ..]) => lookat_matrix([*ex, *ey, *ez], [*ix, *iy, *iz], [*ux, *uy, *uz]), + _ => None, + }; + if let Some(s) = step { + m = mat_mul(&m, &s); + } + } + Ok(m) +} + +fn normalize(v: [f64; 3]) -> Option<[f64; 3]> { + let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt(); + (len.is_finite() && len > 0.0).then(|| v.map(|x| x / len)) +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Option { + let [x, y, z] = normalize(axis)?; + let (s, c) = angle.sin_cos(); + let t = 1.0 - c; + let m = [ + t * x * x + c, + t * x * y + s * z, + t * x * z - s * y, + 0.0, + t * x * y - s * z, + t * y * y + c, + t * y * z + s * x, + 0.0, + t * x * z + s * y, + t * y * z - s * x, + t * z * z + c, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ]; + m.iter().all(|v| v.is_finite()).then_some(m) +} + +fn lookat_matrix(eye: [f64; 3], center: [f64; 3], up: [f64; 3]) -> Option { + let f = normalize([center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]])?; + let s = normalize(cross(f, up))?; + let u = cross(s, f); + let m = [s[0], s[1], s[2], 0.0, u[0], u[1], u[2], 0.0, -f[0], -f[1], -f[2], 0.0, eye[0], eye[1], eye[2], 1.0]; + m.iter().all(|v| v.is_finite()).then_some(m) +} diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index d074f1ed1..5fde04b0a 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -619,6 +619,8 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { let pbr = m.get("pbrMetallicRoughness").unwrap_or(&null); let ext = m.get("extensions"); let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); + let clearcoat = ext.and_then(|e| e.get("KHR_materials_clearcoat")); + let sheen = ext.and_then(|e| e.get("KHR_materials_sheen")); scene.materials.push(Material { name: name(m), base_color: nums(pbr, "baseColorFactor", [1.0; 4]).map(|v| v as f32), @@ -639,6 +641,14 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { occlusion_texture: tref(m.get("occlusionTexture")), occlusion_strength: m.get("occlusionTexture").map_or(1.0, |n| num(n, "strength", 1.0)) as f32, emissive_texture: tref(m.get("emissiveTexture")), + clearcoat: clearcoat.map_or(0.0, |c| num(c, "clearcoatFactor", 0.0)) as f32, + clearcoat_roughness: clearcoat.map_or(0.0, |c| num(c, "clearcoatRoughnessFactor", 0.0)) as f32, + clearcoat_texture: clearcoat.and_then(|c| tref(c.get("clearcoatTexture"))), + clearcoat_roughness_texture: clearcoat.and_then(|c| tref(c.get("clearcoatRoughnessTexture"))), + sheen_color: sheen.map_or([0.0; 3], |s| nums(s, "sheenColorFactor", [0.0; 3]).map(|v| v as f32)), + sheen_roughness: sheen.map_or(0.0, |s| num(s, "sheenRoughnessFactor", 0.0)) as f32, + sheen_color_texture: sheen.and_then(|s| tref(s.get("sheenColorTexture"))), + sheen_roughness_texture: sheen.and_then(|s| tref(s.get("sheenRoughnessTexture"))), }); // The older specular-glossiness model, as the nearest metallic-roughness material: its // diffuse colour and texture, no metal, and roughness from the glossiness. @@ -816,12 +826,14 @@ fn uv_transform(t: &Value) -> UvTransform { /// the reader handles: the geometry reads without the others being understood. fn check_extensions(j: &Value, scene: &mut Scene) -> Result<()> { const LOOKS: [&str; 3] = ["KHR_texture_basisu", "MSFT_texture_dds", "KHR_lights_punctual"]; - const READ: [&str; 6] = [ + const READ: [&str; 8] = [ TEXTURE_TRANSFORM, "KHR_mesh_quantization", "KHR_materials_unlit", "KHR_materials_emissive_strength", "KHR_materials_pbrSpecularGlossiness", + "KHR_materials_clearcoat", + "KHR_materials_sheen", "EXT_texture_webp", ]; for e in arr(j, "extensionsRequired").iter().filter_map(Value::as_str) { @@ -1021,12 +1033,46 @@ fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'s if m.unlit { ext.insert("KHR_materials_unlit".into(), json!({})); } - for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit"] { + if m.clearcoat > 0.0 || m.clearcoat_texture.is_some() || m.clearcoat_roughness_texture.is_some() { + let mut coat = Map::new(); + coat.insert("clearcoatFactor".into(), json!(m.clearcoat)); + if let Some(t) = textures.slot(m.clearcoat_texture) { + coat.insert("clearcoatTexture".into(), t); + } + coat.insert("clearcoatRoughnessFactor".into(), json!(m.clearcoat_roughness)); + if let Some(t) = textures.slot(m.clearcoat_roughness_texture) { + coat.insert("clearcoatRoughnessTexture".into(), t); + } + ext.insert("KHR_materials_clearcoat".into(), Value::Object(coat)); + } + if m.sheen_color != [0.0; 3] || m.sheen_color_texture.is_some() || m.sheen_roughness_texture.is_some() { + let mut sheen = Map::new(); + sheen.insert("sheenColorFactor".into(), json!(m.sheen_color)); + if let Some(t) = textures.slot(m.sheen_color_texture) { + sheen.insert("sheenColorTexture".into(), t); + } + sheen.insert("sheenRoughnessFactor".into(), json!(m.sheen_roughness)); + if let Some(t) = textures.slot(m.sheen_roughness_texture) { + sheen.insert("sheenRoughnessTexture".into(), t); + } + ext.insert("KHR_materials_sheen".into(), Value::Object(sheen)); + } + for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit", "KHR_materials_clearcoat", "KHR_materials_sheen"] { if ext.contains_key(name) && !extensions.contains(&name) { extensions.push(name); } } - let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture]; + let slots = [ + m.base_color_texture, + m.metallic_roughness_texture, + m.normal_texture, + m.occlusion_texture, + m.emissive_texture, + m.clearcoat_texture, + m.clearcoat_roughness_texture, + m.sheen_color_texture, + m.sheen_roughness_texture, + ]; if slots.iter().flatten().any(|t| t.transform.is_some()) && !extensions.contains(&TEXTURE_TRANSFORM) { extensions.push(TEXTURE_TRANSFORM); } @@ -1067,15 +1113,25 @@ fn check_finite(scene: &Scene) -> Result<()> { let positions = scene.meshes.iter().flat_map(|m| m.positions.iter().flatten()).all(|x| (*x as f32).is_finite()); let nodes = scene.nodes.iter().flat_map(|n| n.transform.iter()).all(|x| x.is_finite()); let materials = scene.materials.iter().all(|m| { - let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength]; + let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength, m.clearcoat, m.clearcoat_roughness, m.sheen_roughness]; let cutoff = if let AlphaMode::Mask(c) = m.alpha_mode { c } else { 0.0 }; - let slots = [&m.base_color_texture, &m.metallic_roughness_texture, &m.normal_texture, &m.occlusion_texture, &m.emissive_texture]; + let slots = [ + &m.base_color_texture, + &m.metallic_roughness_texture, + &m.normal_texture, + &m.occlusion_texture, + &m.emissive_texture, + &m.clearcoat_texture, + &m.clearcoat_roughness_texture, + &m.sheen_color_texture, + &m.sheen_roughness_texture, + ]; let transforms = slots .into_iter() .flatten() .filter_map(|t| t.transform) .all(|t| t.offset.iter().chain(&t.scale).chain([&t.rotation]).all(|x| x.is_finite())); - m.base_color.iter().chain(&m.emissive).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms + m.base_color.iter().chain(&m.emissive).chain(&m.sheen_color).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms }); if positions && nodes && materials { Ok(()) } else { Err(malformed(KIND, "a position, transform or material value is not finite")) } } diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index 4808834fa..c1d2e1d4b 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -31,10 +31,23 @@ #![forbid(unsafe_code)] // The helpers the formats share are not all used by every subset of them. #![cfg_attr( - not(all(feature = "stl", feature = "obj", feature = "ply", feature = "gltf", feature = "fbx", feature = "threemf")), + not(all( + feature = "stl", + feature = "obj", + feature = "ply", + feature = "gltf", + feature = "fbx", + feature = "threemf", + feature = "dae", + feature = "abc" + )), allow(dead_code, unused_imports) )] +#[cfg(feature = "abc")] +pub mod abc; +#[cfg(feature = "dae")] +pub mod dae; #[cfg(feature = "fbx")] pub mod fbx; #[cfg(feature = "gltf")] @@ -448,6 +461,16 @@ pub struct Material { pub occlusion_texture: Option, pub occlusion_strength: f32, pub emissive_texture: Option, + /// Clearcoat layer strength in `0..=1` (glTF `KHR_materials_clearcoat`). + pub clearcoat: f32, + pub clearcoat_roughness: f32, + pub clearcoat_texture: Option, + pub clearcoat_roughness_texture: Option, + /// Sheen colour factor (linear RGB) and roughness (glTF `KHR_materials_sheen`). + pub sheen_color: [f32; 3], + pub sheen_roughness: f32, + pub sheen_color_texture: Option, + pub sheen_roughness_texture: Option, } impl Default for Material { @@ -468,6 +491,14 @@ impl Default for Material { occlusion_texture: None, occlusion_strength: 1.0, emissive_texture: None, + clearcoat: 0.0, + clearcoat_roughness: 0.0, + clearcoat_texture: None, + clearcoat_roughness_texture: None, + sheen_color: [0.0; 3], + sheen_roughness: 0.0, + sheen_color_texture: None, + sheen_roughness_texture: None, } } } @@ -742,7 +773,17 @@ impl Scene { } } for m in &self.materials { - let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture]; + let slots = [ + m.base_color_texture, + m.metallic_roughness_texture, + m.normal_texture, + m.occlusion_texture, + m.emissive_texture, + m.clearcoat_texture, + m.clearcoat_roughness_texture, + m.sheen_color_texture, + m.sheen_roughness_texture, + ]; if slots.iter().flatten().any(|t| t.image >= self.images.len()) { return bad(format!("material `{}` names an image that does not exist", m.name)); } diff --git a/crates/mesh/src/obj.rs b/crates/mesh/src/obj.rs index de52bd3f2..a9b52c6cd 100644 --- a/crates/mesh/src/obj.rs +++ b/crates/mesh/src/obj.rs @@ -646,9 +646,15 @@ pub fn write(scene: &Scene, mtllib: Option<&str>, limits: &Limits) -> Result Result<(String, String)> { + Ok((write(scene, Some(mtllib), limits)?, write_mtl(scene))) +} + /// The scene's materials as an MTL library, named as [`fn@write`] names them: `Kd`, `d`, `Ke`, -/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke` -/// and `norm` for images that have a [`Image::uri`]. +/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke`, +/// `norm`, `map_Pc`, and `map_Pcr` for images that have an [`Image::uri`]. pub fn write_mtl(scene: &Scene) -> String { let mut mtl = String::new(); for (m, name) in scene.materials.iter().zip(material_names(scene)) { @@ -661,7 +667,13 @@ pub fn write_mtl(scene: &Scene) -> String { "newmtl {name}\nKd {} {} {}\nd {}\nKe {} {} {}\nNs {ns}\nPr {r}\nPm {}", kd[0], kd[1], kd[2], m.base_color[3], ke[0], ke[1], ke[2], m.metallic ); - for (key, tex) in [("map_Kd", m.base_color_texture), ("map_Ke", m.emissive_texture), ("norm", m.normal_texture)] { + for (key, tex) in [ + ("map_Kd", m.base_color_texture), + ("map_Ke", m.emissive_texture), + ("norm", m.normal_texture), + ("map_Pc", m.clearcoat_texture), + ("map_Pcr", m.clearcoat_roughness_texture), + ] { if let Some(uri) = tex.and_then(|t| scene.images.get(t.image)).and_then(|i| i.uri.as_deref()) { let _ = writeln!(mtl, "{key} {}", uri.replace(['\n', '\r'], " ")); } diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index ae5349775..f2eac7e9f 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -2,6 +2,10 @@ use super::*; +#[cfg(feature = "abc")] +mod abc; +#[cfg(feature = "dae")] +mod dae; #[cfg(feature = "fbx")] mod fbx; #[cfg(feature = "gltf")] diff --git a/crates/mesh/src/tests/abc.rs b/crates/mesh/src/tests/abc.rs new file mode 100644 index 000000000..864ff8261 --- /dev/null +++ b/crates/mesh/src/tests/abc.rs @@ -0,0 +1,198 @@ +use super::*; +use crate::abc::read; + +const DATA_BIT: u64 = 1 << 63; +const OGAWA_MAGIC: &[u8] = b"Ogawa"; +const KEY_BYTES: usize = 16; +const OBJECT_HASH_BYTES: usize = 32; +const F32: u32 = 10; +const I32: u32 = 6; +const U32: u32 = 5; +const U8: u32 = 1; +const F64: u32 = 11; + +struct Writer { + b: Vec, +} + +impl Writer { + fn new() -> Writer { + Writer { b: vec![0; 16] } + } + + fn data(&mut self, bytes: &[u8]) -> u64 { + let at = self.b.len() as u64; + self.b.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + self.b.extend_from_slice(bytes); + at | DATA_BIT + } + + fn group(&mut self, children: &[u64]) -> u64 { + let at = self.b.len() as u64; + self.b.extend_from_slice(&(children.len() as u64).to_le_bytes()); + for c in children { + self.b.extend_from_slice(&c.to_le_bytes()); + } + at + } + + fn finish(mut self, root: u64) -> Vec { + self.b[..5].copy_from_slice(OGAWA_MAGIC); + self.b[5] = 0xff; + self.b[6..8].copy_from_slice(&[0, 1]); + self.b[8..16].copy_from_slice(&root.to_le_bytes()); + self.b + } +} + +struct P { + name: &'static str, + meta: String, + info: u32, + group: u64, +} + +struct Abc { + w: Writer, +} + +impl Abc { + fn sample(&mut self, raw: &[u8]) -> u64 { + let mut v = vec![7u8; KEY_BYTES]; + v.extend_from_slice(raw); + self.w.data(&v) + } + + fn array(&mut self, name: &'static str, meta: &str, pod: u32, extent: u32, raw: &[u8]) -> P { + let (d, dims) = (self.sample(raw), self.w.data(&[])); + let group = self.w.group(&[d, dims]); + P { name, meta: meta.into(), info: 2 | (2 << 2) | (pod << 4) | (extent << 12), group } + } + + fn scalar(&mut self, name: &'static str, pod: u32, extent: u32, raw: &[u8]) -> P { + let d = self.sample(raw); + let group = self.w.group(&[d]); + P { name, meta: String::new(), info: 1 | (2 << 2) | (pod << 4) | (extent << 12), group } + } + + fn compound(&mut self, name: &'static str, meta: &str, props: Vec

) -> P { + let mut header = Vec::new(); + for p in &props { + let info = p.info | (0xff << 20); + header.extend_from_slice(&info.to_le_bytes()); + if info & 3 != 0 { + header.extend_from_slice(&1u32.to_le_bytes()); + } + header.extend_from_slice(&(p.name.len() as u32).to_le_bytes()); + header.extend_from_slice(p.name.as_bytes()); + header.extend_from_slice(&(p.meta.len() as u32).to_le_bytes()); + header.extend_from_slice(p.meta.as_bytes()); + } + let mut children: Vec = props.iter().map(|p| p.group).collect(); + children.push(self.w.data(&header)); + let group = self.w.group(&children); + P { name, meta: meta.into(), info: 2 << 2, group } + } + + fn object(&mut self, props: Vec

, children: &[(&str, &str, u64)]) -> u64 { + let props = self.compound("", "", props).group; + let mut header = Vec::new(); + for (name, meta, _) in children { + header.extend_from_slice(&(name.len() as u32).to_le_bytes()); + header.extend_from_slice(name.as_bytes()); + if meta.is_empty() { + header.push(1); + } else { + header.push(0xff); + header.extend_from_slice(&(meta.len() as u32).to_le_bytes()); + header.extend_from_slice(meta.as_bytes()); + } + } + header.extend_from_slice(&[0; OBJECT_HASH_BYTES]); + let mut kids = vec![props]; + kids.extend(children.iter().map(|c| c.2)); + kids.push(self.w.data(&header)); + self.w.group(&kids) + } + + fn archive(mut self, top: u64, indexed_meta: &[&str]) -> Vec { + let mut im = Vec::new(); + for m in indexed_meta { + im.push(m.len() as u8); + im.extend_from_slice(m.as_bytes()); + } + let kids = [ + self.w.data(&0i32.to_le_bytes()), + self.w.data(&10709i32.to_le_bytes()), + top, + self.w.data(b"_ai_Application=test"), + self.w.data(&[]), + self.w.data(&im), + ]; + let root = self.w.group(&kids); + self.w.finish(root) + } +} + +fn f32s(v: &[f32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn i32s(v: &[i32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn sample_file() -> Vec { + let mut a = Abc { w: Writer::new() }; + let p = f32s(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 1.0, 0.0]); + let indices = i32s(&[0, 3, 4, 1, 1, 4, 5, 2]); + let counts = i32s(&[4, 4]); + let pp = a.array("P", "interpretation=point", F32, 3, &p); + let fi = a.array(".faceIndices", "", I32, 1, &indices); + let fc = a.array(".faceCounts", "", I32, 1, &counts); + let vals = a.array(".vals", "", F32, 2, &f32s(&[0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 1.0])); + let uvi = a.array(".indices", "", U32, 1, &i32s(&[0, 3, 4, 1, 1, 4, 5, 2])); + let uv = a.compound("uv", "geoScope=fvr;podName=float32_t;podExtent=2", vec![vals, uvi]); + let n = a.array("N", "geoScope=vtx", F32, 3, &f32s(&[0.0, 0.0, 1.0].repeat(6))); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv, n]); + let left_faces = a.array(".faces", "", I32, 1, &i32s(&[0])); + let left_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![left_faces]); + let left = a.object(vec![left_fs], &[]); + let right_faces = a.array(".faces", "", I32, 1, &i32s(&[1])); + let right_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![right_faces]); + let right = a.object(vec![right_fs], &[]); + let fs_meta = "schema=AbcGeom_FaceSet_v1;schemaObjTitle=AbcGeom_FaceSet_v1:.faceset"; + let mesh = a.object(vec![geom], &[("left", fs_meta, left), ("right", fs_meta, right)]); + let ops = a.scalar(".ops", U8, 2, &[0x10, 0x00]); + let xv: Vec = [1.0f64, 2.0, 3.0, 2.0, 2.0, 2.0].iter().flat_map(|x| x.to_le_bytes()).collect(); + let vals = a.scalar(".vals", F64, 6, &xv); + let xform = a.compound(".xform", "schema=AbcGeom_Xform_v3", vec![ops, vals]); + let xf = a.object(vec![xform], &[("stripShape", "schema=AbcGeom_PolyMesh_v1;schemaObjTitle=AbcGeom_PolyMesh_v1:.geom", mesh)]); + let top = a.object(vec![], &[("strip", "schema=AbcGeom_Xform_v3", xf)]); + a.archive(top, &["schema=AbcGeom_PolyMesh_v1"]) +} + +#[test] +fn reads_polymesh_xform_face_sets_and_uvs() { + let scene = read(&sample_file(), &Limits::default()).unwrap(); + scene.validate().unwrap(); + assert_eq!(scene.materials.iter().map(|m| m.name.as_str()).collect::>(), ["left", "right"]); + assert_eq!(scene.meshes.len(), 1); + assert_eq!(scene.meshes[0].name, "strip"); + assert_eq!(scene.meshes[0].triangle_count(), 4); + let inst = scene.instances(&Limits::default()).unwrap(); + assert_eq!(inst.len(), 1); + let p0 = transform_point(&inst[0].1, scene.meshes[0].positions[0]); + assert_eq!(p0, [1.0, 2.0, 3.0]); +} + +#[test] +fn hdf5_returns_unsupported() { + let err = read(b"\x89HDF\r\n\x1a\n rest", &Limits::default()).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_))); +} + +#[test] +fn hammer_never_panics() { + hammer(&sample_file(), &|b| read(b, &Limits::default())); +} diff --git a/crates/mesh/src/tests/dae.rs b/crates/mesh/src/tests/dae.rs new file mode 100644 index 000000000..e8883e217 --- /dev/null +++ b/crates/mesh/src/tests/dae.rs @@ -0,0 +1,130 @@ +use super::*; +use crate::dae::{UpAxis, read, read_document}; + +const DAE: &str = r##" + + Z_UP + + + + + + + + + 0 0 0 2 0 0 2 2 0 0 2 0 + + + + 0 0 1 + + + + 0 0 1 0 1 1 0 1 + + + + + + + + 4 +

0 0 0 1 0 1 2 0 2 3 0 3

+ +
+ + + + + 4 0 0 6 0 0 4 2 0 8 0 0 10 0 0 10 2 0 8 2 0 + + + + 0 0 1 0 0 1 0 0 1 0 1 1 0 1 + + + + + + +

0 1 2

+

3 4 5 6

+

0 1

+
+
+ + + 30 + + + + + 0 0 2 + 0 0 1 90 + + 2 2 2 + + + + + + + 0 -10 0 0 0 0 0 0 1 + + + + + + + + + + + +"##; + +#[test] +fn reads_polylist_transforms_units_and_cameras() { + let doc = read_document(DAE.as_bytes(), &Limits::default()).unwrap(); + doc.scene.validate().unwrap(); + assert_eq!(doc.meter, 0.5); + assert_eq!(doc.up_axis, UpAxis::ZUp); + assert_eq!(doc.scene.materials.iter().map(|m| m.name.as_str()).collect::>(), ["Red", "Blue"]); + assert!(doc.scene.warnings.iter().any(|w| w.contains("lines"))); + assert_eq!(doc.scene.cameras.len(), 1); + assert_eq!(doc.scene.cameras[0].name, "Overview"); + + let global = doc.global_transform(); + let inst = doc.scene.instances(&Limits::default()).unwrap(); + assert_eq!(inst.len(), 2); + let mut tris = 0usize; + for (m_idx, xform) in inst { + let m = &doc.scene.meshes[m_idx]; + tris += m.triangle_count(); + let w = mat_mul(&global, &xform); + for p in &m.positions { + let wp = transform_point(&w, *p); + assert!(wp.iter().all(|v| v.is_finite())); + } + } + assert_eq!(tris, 5); +} + +#[test] +fn entities_and_limits_are_enforced() { + let dae = DAE + .replace(r#""#, r#""#) + .replace(r#"name="Red""#, r#"name="R&D""#); + let scene = read(dae.as_bytes(), &Limits::default()).unwrap(); + scene.validate().unwrap(); + assert!(scene.nodes.iter().any(|n| n.name == "Tom & Jerry <\"'AB")); + assert_eq!(scene.materials[0].name, "R&D"); + + let tight = Limits { max_triangles: 2, ..Limits::default() }; + assert!(matches!(read(DAE.as_bytes(), &tight), Err(Error::TooLarge(_)))); +} + +#[test] +fn hammer_never_panics() { + hammer(DAE.as_bytes(), &|b| read(b, &Limits::default())); +} diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index b1200c601..0bd7dddf8 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -482,7 +482,7 @@ fn what_is_not_read_is_refused_or_named() { assert!(matches!(parse(&doc(json!({ "extensionsRequired": ["VENDOR_something_new"] }))), Err(Error::Unsupported(_)))); // Extensions that only change looks are named in a warning; the ones the reader handles are not. let s = parse(&doc( - json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_clearcoat", "KHR_mesh_quantization", "KHR_materials_unlit"] }), + json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_transmission", "KHR_mesh_quantization", "KHR_materials_unlit"] }), )) .unwrap(); assert_eq!(s.warnings.len(), 1, "texture transforms are read: {:?}", s.warnings); @@ -953,3 +953,38 @@ fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { assert_eq!(decoded, "A%GG+é".repeat(100_000)); assert!(decoded.len() <= input.len()); } + +#[test] +fn clearcoat_and_sheen_round_trip_through_write_glb() { + let mut mesh = Mesh { name: "card".into(), ..Mesh::default() }; + mesh.positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + mesh.parts = vec![Part { material: Some(0), corners: [0, 1, 2].map(Corner::at).to_vec(), ..Part::default() }]; + let mat = Material { + name: "CoatedVelvet".into(), + clearcoat: 0.8, + clearcoat_roughness: 0.25, + clearcoat_texture: Some(TextureRef { image: 0, ..TextureRef::default() }), + clearcoat_roughness_texture: Some(TextureRef { image: 0, ..TextureRef::default() }), + sheen_color: [0.9, 0.2, 0.1], + sheen_roughness: 0.5, + sheen_color_texture: Some(TextureRef { image: 1, ..TextureRef::default() }), + sheen_roughness_texture: Some(TextureRef { image: 1, ..TextureRef::default() }), + ..Material::default() + }; + let mut scene = Scene::from_meshes(vec![mesh], vec![mat.clone()]); + scene.images = vec![ + Image { name: "coat".into(), data: Some(b"\x89PNG coat".to_vec()), ..Image::default() }, + Image { name: "sheen".into(), data: Some(b"\x89PNG sheen".to_vec()), ..Image::default() }, + ]; + let glb = write_glb(&scene, &Limits::default()).unwrap(); + let back = parse(&glb).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(back.materials[0].clearcoat, mat.clearcoat); + assert_eq!(back.materials[0].clearcoat_roughness, mat.clearcoat_roughness); + assert_eq!(back.materials[0].clearcoat_texture.map(|t| t.image), Some(0)); + assert_eq!(back.materials[0].clearcoat_roughness_texture.map(|t| t.image), Some(0)); + assert_eq!(back.materials[0].sheen_color, mat.sheen_color); + assert_eq!(back.materials[0].sheen_roughness, mat.sheen_roughness); + assert_eq!(back.materials[0].sheen_color_texture.map(|t| t.image), Some(1)); + assert_eq!(back.materials[0].sheen_roughness_texture.map(|t| t.image), Some(1)); +} diff --git a/crates/mesh/src/tests/obj.rs b/crates/mesh/src/tests/obj.rs index e91549fd1..b13dfd366 100644 --- a/crates/mesh/src/tests/obj.rs +++ b/crates/mesh/src/tests/obj.rs @@ -1,6 +1,6 @@ use super::hammer; use crate::obj::{material_names, read, read_mtl, sibling_name, write, write_mtl}; -use crate::{AlphaMode, Corner, Error, Limits, Material, Mesh, NONE, Part, Scene, no_external}; +use crate::{AlphaMode, Corner, Error, Image, Limits, Material, Mesh, NONE, Part, Scene, TextureRef, no_external}; /// A unit cube with texture coordinates, normals, two materials and one face written with /// negative references. @@ -364,3 +364,14 @@ fn group_boundaries_keep_repeated_names_separate() { assert_eq!(scene.meshes.len(), 2); assert!(scene.meshes.iter().all(|m| m.name == "Same")); } + +#[test] +fn write_with_mtl_links_library_and_clearcoat_maps() { + let mut scene = cube(); + scene.images = vec![Image { uri: Some("coat.png".into()), ..Image::default() }]; + scene.materials[0].clearcoat_texture = Some(TextureRef { image: 0, ..TextureRef::default() }); + scene.materials[0].clearcoat_roughness_texture = Some(TextureRef { image: 0, ..TextureRef::default() }); + let (obj, mtl) = crate::obj::write_with_mtl(&scene, "cube.mtl", &Limits::default()).unwrap(); + assert!(obj.contains("mtllib cube.mtl\n")); + assert!(mtl.contains("map_Pc coat.png\n") && mtl.contains("map_Pcr coat.png\n"), "{mtl}"); +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 1cb28d922..9cfb7e7ce 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -30,6 +30,8 @@ content = ["cos", "dep:hayro-syntax"] crypt = ["dep:aes", "dep:md-5", "dep:sha2", "dep:stringprep", "dep:zeroize", "dep:thiserror"] # `testing`: a builder of small synthetic PDF files, for the tests of crates that read them. test-support = ["cos"] +# Standard-14 font metrics and ISO 32000-2 Annex D single-byte encodings. +fonts = [] [dependencies] hayro-syntax = { workspace = true, optional = true } diff --git a/crates/pdf/src/fonts.rs b/crates/pdf/src/fonts.rs new file mode 100644 index 000000000..4a880d180 --- /dev/null +++ b/crates/pdf/src/fonts.rs @@ -0,0 +1,180 @@ +//! PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap encoding helpers, +//! and Standard-14 font metrics. + +pub mod encodings; +mod std14; +mod std14_metrics; + +pub use std14::{Match as Std14Match, Std14}; + +/// The WinAnsiEncoding (ISO 32000-2 Annex D) code for `c`, if the encoding has one. +/// +/// Codes 0x80–0x9F come from the same table the text extractor decodes with, so encoding and +/// decoding agree (Š š Ž ž Œ œ Ÿ ƒ † ‡ ˆ ˜ ‰ ‹ › as well as quotes, dashes, € and ™). +pub fn win_ansi_byte(c: char) -> Option { + match c { + '\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => u8::try_from(u32::from(c)).ok(), + _ => { + let high = encodings::WIN_ANSI.get(0x80..0xa0)?; + let i = high.iter().position(|&u| u != 0 && u == u32::from(c))?; + u8::try_from(0x80 + i).ok() + } + } +} + +/// Encode text in WinAnsiEncoding (ISO 32000-2 Annex D); tabs become spaces and unmappable +/// characters become `?`. +pub fn win_ansi(s: &str) -> Vec { + s.chars().map(|c| if c == '\t' { b' ' } else { win_ansi_byte(c).unwrap_or(b'?') }).collect() +} + +/// The byte used by Unicode text plans, from the shared WinAnsi table (tabs become spaces). +pub fn win_ansi_char(c: char) -> Option { + if c == '\t' { Some(b' ') } else { win_ansi_byte(c) } +} + +/// Whether [`win_ansi`] keeps `c` rather than writing `?` (a tab becomes a space). +pub fn win_ansi_encodable(c: char) -> bool { + c == '\t' || win_ansi_byte(c).is_some() +} + +/// The first character of `s` that [`win_ansi`] can't encode and would write as `?`. +pub fn first_non_win_ansi(s: &str) -> Option { + s.chars().find(|c| !win_ansi_encodable(*c)) +} + +/// Whether every character can be represented without substitution in WinAnsi. +pub fn fits_win_ansi(s: &str) -> bool { + s.chars().all(win_ansi_encodable) +} + +/// The character encoding of a predefined Unicode CMap (`UniJIS-UTF16-H`, `UniGB-UCS2-H`, …; +/// ISO 32000-2 §9.7.5.2), which maps Unicode text straight to codes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnicodeCMap { + Ucs2, + Utf16, + Utf8, + Utf32, +} + +impl UnicodeCMap { + /// The encoding of the predefined CMap `name`, if it is a horizontal Unicode one. Vertical + /// (`-V`) CMaps are refused: field appearances are laid out horizontally, so their glyphs + /// would be drawn stacked down the field instead of across it. + pub fn from_name(name: &[u8]) -> Option { + let name = std::str::from_utf8(name).ok()?; + if !name.starts_with("Uni") || !name.ends_with("-H") { + return None; + } + name.split('-').find_map(|part| match part { + "UCS2" => Some(Self::Ucs2), + "UTF16" => Some(Self::Utf16), + "UTF8" => Some(Self::Utf8), + "UTF32" => Some(Self::Utf32), + _ => None, + }) + } + + /// The first character of `s` this encoding can't hold, which [`Self::encode`] would write as + /// `?`: a character beyond U+FFFF in UCS-2 (`𠀋`). UTF-16, UTF-8 and UTF-32 hold every one. + pub fn first_unencodable(self, s: &str) -> Option { + match self { + Self::Ucs2 => s.chars().find(|c| u16::try_from(u32::from(*c)).is_err()), + Self::Utf16 | Self::Utf8 | Self::Utf32 => None, + } + } + + /// Encode `s`; tabs become spaces, and characters UCS-2 can't hold become `?` (check them + /// first with [`Self::first_unencodable`]: callers should refuse such text rather than write `?`). + pub fn encode(self, s: &str) -> Vec { + let mut out = Vec::with_capacity(s.len().saturating_mul(2)); + let mut units = [0u16; 2]; + let mut buf = [0u8; 4]; + for c in s.chars() { + let c = if c == '\t' { ' ' } else { c }; + match self { + Self::Ucs2 => { + let unit = u16::try_from(u32::from(c)).unwrap_or(u16::from(b'?')); + out.extend_from_slice(&unit.to_be_bytes()); + } + Self::Utf16 => { + for unit in c.encode_utf16(&mut units) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()), + Self::Utf32 => out.extend_from_slice(&u32::from(c).to_be_bytes()), + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_alias_codes_read_as_the_glyph_they_draw() { + assert_eq!(encodings::WIN_ANSI.get(0xAD), Some(&u32::from('-'))); + assert_eq!(encodings::WIN_ANSI.get(0x2D), Some(&u32::from('-'))); + assert_eq!(encodings::WIN_ANSI.get(0xA0), Some(&u32::from(' '))); + assert_eq!(encodings::WIN_ANSI.get(0x20), Some(&u32::from(' '))); + assert_eq!(encodings::MAC_ROMAN.get(0xCA), Some(&u32::from(' '))); + assert_eq!(encodings::MAC_ROMAN.get(0x20), Some(&u32::from(' '))); + // MacRoman has no soft hyphen; 0xAD there is `notequal`, and keeps it. + assert_eq!(encodings::MAC_ROMAN.get(0xAD), Some(&0x2260)); + // Writing is unaffected: '-' and ' ' take the canonical low codes, and a caller holding a + // literal U+00AD or U+00A0 still writes the high byte, which is the one that draws them. + assert_eq!(win_ansi_byte('-'), Some(0x2D)); + assert_eq!(win_ansi_byte(' '), Some(0x20)); + assert_eq!(win_ansi_byte('\u{00ad}'), Some(0xAD)); + assert_eq!(win_ansi_byte('\u{00a0}'), Some(0xA0)); + assert_eq!(win_ansi("a-b c"), b"a-b c"); + } + + #[test] + fn win_ansi_covers_the_0x80_to_0x9f_glyphs() { + const ALIASES: &[u8] = &[0xA0, 0xAD]; + for (code, &u) in encodings::WIN_ANSI.iter().enumerate() { + let Some(c) = char::from_u32(u).filter(|_| u != 0) else { continue }; + if ALIASES.contains(&(code as u8)) { + let canonical = win_ansi_byte(c).expect("an aliased glyph still encodes"); + assert!(canonical < code as u8, "{c:?}: the canonical code is the lower one"); + assert_eq!(encodings::WIN_ANSI.get(usize::from(canonical)), Some(&u), "both codes mean the same character"); + continue; + } + assert_eq!(win_ansi_byte(c), Some(code as u8), "{c:?} (U+{u:04X})"); + assert_eq!(win_ansi(&c.to_string()), [code as u8]); + } + assert_eq!( + win_ansi("Šta? žaba, œuvre — „ok“ ‰ ƒ † ‡ ˆ ˜ ‹›Ÿ"), + b"\x8ata? \x9eaba, \x9cuvre \x97 \x84ok\x93 \x89 \x83 \x86 \x87 \x88 \x98 \x8b\x9b\x9f" + ); + assert_eq!(win_ansi("čć\u{81}\u{8d}\t"), b"???? "); + assert_eq!(win_ansi_byte('\0'), None); + } + + #[test] + fn unicode_cmaps_encode_cjk_text() { + assert_eq!(UnicodeCMap::from_name(b"UniJIS-UTF16-H"), Some(UnicodeCMap::Utf16)); + assert_eq!(UnicodeCMap::from_name(b"UniGB-UCS2-V"), None); + assert_eq!(UnicodeCMap::from_name(b"UniJIS-UCS2-HW-H"), Some(UnicodeCMap::Ucs2)); + assert_eq!(UnicodeCMap::from_name(b"UniKS-UTF8-H"), Some(UnicodeCMap::Utf8)); + assert_eq!(UnicodeCMap::from_name(b"UniJIS2004-UTF32-H"), Some(UnicodeCMap::Utf32)); + assert_eq!(UnicodeCMap::from_name(b"Identity-H"), None); + assert_eq!(UnicodeCMap::from_name(b"90ms-RKSJ-H"), None); + assert_eq!(UnicodeCMap::from_name(b"\xff\xfe"), None); + assert_eq!(UnicodeCMap::Utf16.encode("令A"), [0x4e, 0xe4, 0x00, 0x41]); + assert_eq!(UnicodeCMap::Utf16.encode("𠀋"), [0xd8, 0x40, 0xdc, 0x0b]); + assert_eq!(UnicodeCMap::Ucs2.encode("𠀋\t"), [0x00, b'?', 0x00, b' ']); + assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和𠀋"), Some('𠀋')); + assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和"), None); + for cmap in [UnicodeCMap::Utf16, UnicodeCMap::Utf8, UnicodeCMap::Utf32] { + assert_eq!(cmap.first_unencodable("令和𠀋"), None, "{cmap:?}"); + } + assert_eq!(UnicodeCMap::Utf8.encode("令"), "令".as_bytes()); + assert_eq!(UnicodeCMap::Utf32.encode("令"), [0, 0, 0x4e, 0xe4]); + } +} diff --git a/crates/pdf/src/fonts/encodings.rs b/crates/pdf/src/fonts/encodings.rs new file mode 100644 index 000000000..676d573ab --- /dev/null +++ b/crates/pdf/src/fonts/encodings.rs @@ -0,0 +1,275 @@ +//! Single-byte encodings (ISO 32000-2 Annex D) as code → Unicode tables (0 = undefined). + +pub static WIN_ANSI: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, + // 0xA0 is `space` and 0xAD is `hyphen`, not U+00A0 and U+00AD: WinAnsiEncoding's table + // (Annex D.2) gives those codes the same glyph names as 0x20 and 0x2D, so the bytes a Windows + // codepage calls a non-breaking space and a soft hyphen draw, and extract as, an ordinary + // space and hyphen. Emitting the formatting characters instead hides them from search and + // from redaction's pattern matching: a soft hyphen is invisible and matches nothing, and a + // non-breaking space does not match the space a reader typed. + 0, 381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 0, 382, 376, 32, 161, 162, 163, 164, 165, 166, 167, 168, 169, + 170, 171, 172, 45, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, + 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, + 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, +]; +pub static MAC_ROMAN: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 196, 197, 199, 201, 209, 214, 220, 225, 224, 226, 228, 227, 229, 231, + 233, 232, 234, 235, 237, 236, 238, 239, 241, 243, 242, 244, 246, 245, 250, 249, 251, 252, 8224, 176, 162, 163, 167, 8226, 182, 223, 174, 169, + 8482, 180, 168, 8800, 198, 216, 8734, 177, 8804, 8805, 165, 181, 8706, 8721, 8719, 960, 8747, 170, 186, 937, 230, 248, 191, 161, 172, 8730, 402, + // 0xCA is `space`, the same glyph name Annex D.2 gives 0x20, for the reason WinAnsi 0xA0 is. + 8776, 8710, 171, 187, 8230, 32, 192, 195, 213, 338, 339, 8211, 8212, 8220, 8221, 8216, 8217, 247, 9674, 255, 376, 8260, 8364, 8249, 8250, 64257, + 64258, 8225, 183, 8218, 8222, 8240, 194, 202, 193, 203, 200, 205, 206, 207, 204, 211, 212, 63743, 210, 218, 219, 217, 305, 710, 732, 175, 728, + 729, 730, 184, 733, 731, 711, +]; +pub static STANDARD: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 8217, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 8216, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 161, 162, 163, 8260, 165, 402, 167, 164, 39, 8220, 171, 8249, 8250, 64257, 64258, 0, 8211, 8224, 8225, 183, 0, + 182, 8226, 8218, 8222, 8221, 187, 8230, 8240, 0, 191, 0, 96, 180, 710, 732, 175, 728, 729, 168, 0, 730, 184, 0, 733, 731, 711, 8212, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 0, 170, 0, 0, 0, 0, 321, 216, 338, 186, 0, 0, 0, 0, 0, 230, 0, 0, 0, 305, 0, 0, 322, 248, 339, 223, 0, + 0, 0, 0, +]; + +/// Glyph names of the Latin character set (Annex D) → Unicode. +pub static NAMES: &[(&str, u32)] = &[ + ("A", 0x41), + ("AE", 0xc6), + ("Aacute", 0xc1), + ("Acircumflex", 0xc2), + ("Adieresis", 0xc4), + ("Agrave", 0xc0), + ("Aring", 0xc5), + ("Atilde", 0xc3), + ("B", 0x42), + ("C", 0x43), + ("Ccedilla", 0xc7), + ("D", 0x44), + ("E", 0x45), + ("Eacute", 0xc9), + ("Ecircumflex", 0xca), + ("Edieresis", 0xcb), + ("Egrave", 0xc8), + ("Eth", 0xd0), + ("Euro", 0x20ac), + ("F", 0x46), + ("G", 0x47), + ("H", 0x48), + ("I", 0x49), + ("Iacute", 0xcd), + ("Icircumflex", 0xce), + ("Idieresis", 0xcf), + ("Igrave", 0xcc), + ("J", 0x4a), + ("K", 0x4b), + ("L", 0x4c), + ("Lslash", 0x141), + ("M", 0x4d), + ("N", 0x4e), + ("Ntilde", 0xd1), + ("O", 0x4f), + ("OE", 0x152), + ("Oacute", 0xd3), + ("Ocircumflex", 0xd4), + ("Odieresis", 0xd6), + ("Ograve", 0xd2), + ("Oslash", 0xd8), + ("Otilde", 0xd5), + ("P", 0x50), + ("Q", 0x51), + ("R", 0x52), + ("S", 0x53), + ("Scaron", 0x160), + ("T", 0x54), + ("Thorn", 0xde), + ("U", 0x55), + ("Uacute", 0xda), + ("Ucircumflex", 0xdb), + ("Udieresis", 0xdc), + ("Ugrave", 0xd9), + ("V", 0x56), + ("W", 0x57), + ("X", 0x58), + ("Y", 0x59), + ("Yacute", 0xdd), + ("Ydieresis", 0x178), + ("Z", 0x5a), + ("Zcaron", 0x17d), + ("a", 0x61), + ("aacute", 0xe1), + ("acircumflex", 0xe2), + ("acute", 0xb4), + ("adieresis", 0xe4), + ("ae", 0xe6), + ("agrave", 0xe0), + ("ampersand", 0x26), + ("aring", 0xe5), + ("asciicircum", 0x5e), + ("asciitilde", 0x7e), + ("asterisk", 0x2a), + ("at", 0x40), + ("atilde", 0xe3), + ("b", 0x62), + ("backslash", 0x5c), + ("bar", 0x7c), + ("braceleft", 0x7b), + ("braceright", 0x7d), + ("bracketleft", 0x5b), + ("bracketright", 0x5d), + ("breve", 0x2d8), + ("brokenbar", 0xa6), + ("bullet", 0x2022), + ("c", 0x63), + ("caron", 0x2c7), + ("ccedilla", 0xe7), + ("cedilla", 0xb8), + ("cent", 0xa2), + ("circumflex", 0x2c6), + ("colon", 0x3a), + ("comma", 0x2c), + ("copyright", 0xa9), + ("currency", 0xa4), + ("d", 0x64), + ("dagger", 0x2020), + ("daggerdbl", 0x2021), + ("degree", 0xb0), + ("dieresis", 0xa8), + ("divide", 0xf7), + ("dollar", 0x24), + ("dotaccent", 0x2d9), + ("dotlessi", 0x131), + ("e", 0x65), + ("eacute", 0xe9), + ("ecircumflex", 0xea), + ("edieresis", 0xeb), + ("egrave", 0xe8), + ("eight", 0x38), + ("ellipsis", 0x2026), + ("emdash", 0x2014), + ("endash", 0x2013), + ("equal", 0x3d), + ("eth", 0xf0), + ("exclam", 0x21), + ("exclamdown", 0xa1), + ("f", 0x66), + ("fi", 0xfb01), + ("five", 0x35), + ("fl", 0xfb02), + ("florin", 0x192), + ("four", 0x34), + ("fraction", 0x2044), + ("g", 0x67), + ("germandbls", 0xdf), + ("grave", 0x60), + ("greater", 0x3e), + ("guillemotleft", 0xab), + ("guillemotright", 0xbb), + ("guilsinglleft", 0x2039), + ("guilsinglright", 0x203a), + ("h", 0x68), + ("hungarumlaut", 0x2dd), + ("hyphen", 0x2d), + ("i", 0x69), + ("iacute", 0xed), + ("icircumflex", 0xee), + ("idieresis", 0xef), + ("igrave", 0xec), + ("j", 0x6a), + ("k", 0x6b), + ("l", 0x6c), + ("less", 0x3c), + ("logicalnot", 0xac), + ("lslash", 0x142), + ("m", 0x6d), + ("macron", 0xaf), + ("minus", 0x2212), + ("mu", 0xb5), + ("multiply", 0xd7), + ("n", 0x6e), + ("nbspace", 0xa0), + ("nine", 0x39), + ("ntilde", 0xf1), + ("numbersign", 0x23), + ("o", 0x6f), + ("oacute", 0xf3), + ("ocircumflex", 0xf4), + ("odieresis", 0xf6), + ("oe", 0x153), + ("ogonek", 0x2db), + ("ograve", 0xf2), + ("one", 0x31), + ("onehalf", 0xbd), + ("onequarter", 0xbc), + ("onesuperior", 0xb9), + ("ordfeminine", 0xaa), + ("ordmasculine", 0xba), + ("oslash", 0xf8), + ("otilde", 0xf5), + ("p", 0x70), + ("paragraph", 0xb6), + ("parenleft", 0x28), + ("parenright", 0x29), + ("percent", 0x25), + ("period", 0x2e), + ("periodcentered", 0xb7), + ("perthousand", 0x2030), + ("plus", 0x2b), + ("plusminus", 0xb1), + ("q", 0x71), + ("question", 0x3f), + ("questiondown", 0xbf), + ("quotedbl", 0x22), + ("quotedblbase", 0x201e), + ("quotedblleft", 0x201c), + ("quotedblright", 0x201d), + ("quoteleft", 0x2018), + ("quoteright", 0x2019), + ("quotesinglbase", 0x201a), + ("quotesingle", 0x27), + ("r", 0x72), + ("registered", 0xae), + ("ring", 0x2da), + ("s", 0x73), + ("scaron", 0x161), + ("section", 0xa7), + ("semicolon", 0x3b), + ("seven", 0x37), + ("sfthyphen", 0xad), + ("six", 0x36), + ("slash", 0x2f), + ("space", 0x20), + ("sterling", 0xa3), + ("t", 0x74), + ("thorn", 0xfe), + ("three", 0x33), + ("threequarters", 0xbe), + ("threesuperior", 0xb3), + ("tilde", 0x2dc), + ("trademark", 0x2122), + ("two", 0x32), + ("twosuperior", 0xb2), + ("u", 0x75), + ("uacute", 0xfa), + ("ucircumflex", 0xfb), + ("udieresis", 0xfc), + ("ugrave", 0xf9), + ("underscore", 0x5f), + ("v", 0x76), + ("w", 0x77), + ("x", 0x78), + ("y", 0x79), + ("yacute", 0xfd), + ("ydieresis", 0xff), + ("yen", 0xa5), + ("z", 0x7a), + ("zcaron", 0x17e), + ("zero", 0x30), +]; diff --git a/crates/pdf/src/fonts/std14.rs b/crates/pdf/src/fonts/std14.rs new file mode 100644 index 000000000..ac68c95c6 --- /dev/null +++ b/crates/pdf/src/fonts/std14.rs @@ -0,0 +1,260 @@ +//! Standard-14 font metrics (ISO 32000-2 Annex D; the Adobe Core14 AFM metrics), as advance +//! widths in glyph space — thousandths of an em. +//! +//! A PDF may name any of the fourteen standard fonts without embedding a program, and the viewer +//! has to supply the metrics. These are those metrics, exactly, replacing the character-class +//! estimate that generated appearances used before: that estimate had Times at 0.9 x Helvetica, +//! which makes a capital A 600 where the specification says 722. +//! +//! **Generated.** The tables are data, not typefaces, and are the item AGENTS.md §1.1 permits as +//! Adobe-authored non-visual technical data; `ATTRIBUTION.toml` carries the entry with +//! `adobe_data = true`. Each row is indexed by character **code**, not by Unicode: the twelve text +//! fonts are indexed by WinAnsiEncoding, which is what PdfCraft writes into the appearance streams +//! it generates, and Symbol and ZapfDingbats by their own built-in encodings. A zero means the +//! encoding leaves that code undefined. + +/// One of the fourteen standard fonts (ISO 32000-2 §9.6.2.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Std14 { + Helvetica, + HelveticaBold, + HelveticaOblique, + HelveticaBoldOblique, + TimesRoman, + TimesBold, + TimesItalic, + TimesBoldItalic, + Courier, + CourierBold, + CourierOblique, + CourierBoldOblique, + Symbol, + ZapfDingbats, +} + +/// How [`Std14::recognise`] matched a `/BaseFont` name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Match { + /// A standard-14 face or a well-known alias of one (Arial for Helvetica, CourierNew for + /// Courier). The document is asking for this face. + Alias, + /// Only a family hint matched -- "Serif", "Roman" or "Mono" in an otherwise unknown name. + /// The face is a guess from the name, not the one the document asked for. + FamilyHint, +} + +impl Std14 { + /// The font a `/BaseFont` name selects, by the spec's names and the common aliases viewers + /// accept (`Arial` for `Helvetica`, `TimesNewRoman` for `Times`, `CourierNew` for `Courier`). + /// A subset prefix such as `ABCDEF+Helvetica` is ignored. + pub fn from_base_font(base: &str) -> Option { + Self::recognise(base).map(|(face, _)| face) + } + + /// [`Std14::from_base_font`], also saying *how* the name matched. + /// + /// Reporting needs the difference. "Arial" really is a request for Helvetica, but + /// "SomeHouseSerif" is a house font whose name merely contains "Serif"; choosing Times for it + /// is a reasonable guess from the name, not the face the document asked for, and a substitution + /// report that called it a standard-14 name would be telling the reader something untrue. + pub fn recognise(base: &str) -> Option<(Self, Match)> { + let base = base.rsplit('+').next().unwrap_or(base); + let flat: String = base.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect(); + let has = |w: &str| flat.contains(w); + let (bold, italic) = (has("bold"), has("italic") || has("oblique")); + // Two bools index a four-element array, so the subscript is provably 0..=3. + let styled = |faces: [Self; 4]| faces[usize::from(bold) | usize::from(italic) << 1]; + let courier = || styled([Self::Courier, Self::CourierBold, Self::CourierOblique, Self::CourierBoldOblique]); + let times = || styled([Self::TimesRoman, Self::TimesBold, Self::TimesItalic, Self::TimesBoldItalic]); + if has("symbol") { + return Some((Self::Symbol, Match::Alias)); + } + if has("zapf") || has("dingbat") { + return Some((Self::ZapfDingbats, Match::Alias)); + } + if has("courier") { + return Some((courier(), Match::Alias)); + } + if has("mono") { + return Some((courier(), Match::FamilyHint)); + } + if has("times") { + return Some((times(), Match::Alias)); + } + if (has("serif") && !has("sans")) || has("roman") { + return Some((times(), Match::FamilyHint)); + } + if has("helvetica") || has("arial") { + return Some((styled([Self::Helvetica, Self::HelveticaBold, Self::HelveticaOblique, Self::HelveticaBoldOblique]), Match::Alias)); + } + None + } + + /// The advance of one character `code`, in thousandths of an em. Zero where the font's + /// encoding leaves the code undefined. + pub fn width(self, code: u8) -> f64 { + f64::from(super::std14_metrics::WIDTHS[self as usize][code as usize]) + } + + /// The advance of `code` at `size` points. + pub fn advance(self, code: u8, size: f64) -> f64 { + self.width(code) * size / 1000.0 + } + + /// The advance of `text` at `size` points, encoded as the twelve text fonts are written: + /// WinAnsiEncoding, with characters it cannot represent replaced as `win_ansi` replaces them. + /// + /// Symbol and ZapfDingbats have their own built-in encodings and are not WinAnsi, so this + /// measures them as if they were; pass codes to [`Std14::width`] for those. + pub fn text_width(self, text: &str, size: f64) -> f64 { + super::win_ansi(text).iter().map(|&c| self.width(c)).sum::() * size / 1000.0 + } + + /// Courier is the only fixed-pitch family of the fourteen. + pub fn is_fixed_pitch(self) -> bool { + matches!(self, Self::Courier | Self::CourierBold | Self::CourierOblique | Self::CourierBoldOblique) + } + + /// The `/BaseFont` name for this font, as it is written into a PDF. + pub fn base_font(self) -> &'static str { + super::std14_metrics::BASE_FONTS[self as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sans_serif_names_are_not_mapped_to_times() { + assert!(!matches!(Std14::recognise("SansSerif"), Some((Std14::TimesRoman, _)))); + assert_eq!(Std14::recognise("Arial-SansSerif"), Some((Std14::Helvetica, Match::Alias))); + } + + /// Widths from the published Core14 metrics, typed in here by hand so the table is checked + /// against the specification rather than against whatever produced it. + #[test] + fn widths_match_the_published_metrics() { + let cases: &[(Std14, char, u16)] = &[ + // Helvetica + (Std14::Helvetica, ' ', 278), + (Std14::Helvetica, 'A', 667), + (Std14::Helvetica, 'W', 944), + (Std14::Helvetica, 'i', 222), + (Std14::Helvetica, 'm', 833), + (Std14::Helvetica, '0', 556), + (Std14::Helvetica, '@', 1015), + (Std14::HelveticaBold, 'A', 722), + (Std14::HelveticaBold, 'i', 278), + // Times: not Helvetica scaled by 0.9, which is what the old estimate assumed. + (Std14::TimesRoman, ' ', 250), + (Std14::TimesRoman, 'A', 722), + (Std14::TimesRoman, 'W', 944), + (Std14::TimesRoman, 'i', 278), + (Std14::TimesRoman, 'm', 778), + (Std14::TimesBold, 'A', 722), + (Std14::TimesItalic, 'A', 611), + // Courier is fixed pitch at 600 for every glyph. + (Std14::Courier, ' ', 600), + (Std14::Courier, 'A', 600), + (Std14::Courier, 'm', 600), + (Std14::CourierBoldOblique, 'W', 600), + ]; + for &(font, ch, want) in cases { + let code = crate::fonts::win_ansi(&ch.to_string()); + assert_eq!(code.len(), 1, "{ch:?} is one WinAnsi byte"); + assert_eq!(font.width(code[0]) as u16, want, "{font:?} {ch:?}"); + } + } + + #[test] + fn courier_is_fixed_pitch_everywhere_it_is_defined() { + for font in [Std14::Courier, Std14::CourierBold, Std14::CourierOblique, Std14::CourierBoldOblique] { + assert!(font.is_fixed_pitch()); + for code in 0..=255u8 { + let w = font.width(code); + assert!(w == 0.0 || w == 600.0, "{font:?} code {code} has width {w}"); + } + } + assert!(!Std14::Helvetica.is_fixed_pitch()); + } + + #[test] + fn every_text_font_covers_printable_ascii_and_latin1() { + for font in [Std14::Helvetica, Std14::TimesRoman, Std14::Courier, Std14::TimesBoldItalic] { + for code in 0x20..=0x7Eu8 { + assert!(font.width(code) > 0.0, "{font:?} has no width for ASCII {code}"); + } + for code in 0xA0..=0xFFu8 { + assert!(font.width(code) > 0.0, "{font:?} has no width for Latin-1 {code}"); + } + } + } + + #[test] + fn symbol_and_dingbats_have_their_own_encodings() { + // Symbol's code 0x61 is alpha, not 'a'; ZapfDingbats' is a scissors glyph. + assert!(Std14::Symbol.width(0x61) > 0.0); + assert!(Std14::ZapfDingbats.width(0x61) > 0.0); + // Neither defines the Latin-1 upper half the text fonts do. + assert_eq!(Std14::Symbol.width(0xFF), 0.0); + } + + #[test] + fn base_font_names_round_trip() { + for i in 0..14usize { + let font = [ + Std14::Helvetica, + Std14::HelveticaBold, + Std14::HelveticaOblique, + Std14::HelveticaBoldOblique, + Std14::TimesRoman, + Std14::TimesBold, + Std14::TimesItalic, + Std14::TimesBoldItalic, + Std14::Courier, + Std14::CourierBold, + Std14::CourierOblique, + Std14::CourierBoldOblique, + Std14::Symbol, + Std14::ZapfDingbats, + ][i]; + assert_eq!(Std14::from_base_font(font.base_font()), Some(font), "{}", font.base_font()); + } + } + + #[test] + fn base_font_aliases_and_subset_prefixes_resolve() { + assert_eq!(Std14::from_base_font("ABCDEF+Helvetica-Bold"), Some(Std14::HelveticaBold)); + assert_eq!(Std14::from_base_font("Arial"), Some(Std14::Helvetica)); + assert_eq!(Std14::from_base_font("Arial,BoldItalic"), Some(Std14::HelveticaBoldOblique)); + assert_eq!(Std14::from_base_font("TimesNewRoman,Bold"), Some(Std14::TimesBold)); + assert_eq!(Std14::from_base_font("CourierNew-Oblique"), Some(Std14::CourierOblique)); + assert_eq!(Std14::from_base_font("ZapfDingbats"), Some(Std14::ZapfDingbats)); + assert_eq!(Std14::from_base_font("Wingdings"), None); + assert_eq!(Std14::from_base_font(""), None); + } + + #[test] + fn text_width_sums_the_glyphs_and_scales_with_size() { + let h = Std14::Helvetica; + // "AW" = 667 + 944 = 1611 thousandths of an em. + assert!((h.text_width("AW", 1000.0) - 1611.0).abs() < 1e-9); + assert!((h.text_width("AW", 12.0) - 1611.0 * 12.0 / 1000.0).abs() < 1e-9); + assert_eq!(h.text_width("", 12.0), 0.0); + // Courier: every character is 600, so the width is purely a count. + assert!((Std14::Courier.text_width("hello", 10.0) - 5.0 * 6.0).abs() < 1e-9); + } + + #[test] + fn hostile_text_does_not_panic_and_stays_finite() { + for font in [Std14::Helvetica, Std14::Symbol, Std14::Courier] { + for s in ["", "\0", "\u{202E}", "💥", &"a".repeat(10_000), "\u{FFFD}"] { + let w = font.text_width(s, 12.0); + assert!(w.is_finite() && w >= 0.0, "{font:?} {s:?} -> {w}"); + } + assert!(font.advance(0, 12.0).is_finite()); + assert!(font.advance(255, 0.0).is_finite()); + } + } +} diff --git a/crates/pdf/src/fonts/std14_metrics.rs b/crates/pdf/src/fonts/std14_metrics.rs new file mode 100644 index 000000000..05ba41c71 --- /dev/null +++ b/crates/pdf/src/fonts/std14_metrics.rs @@ -0,0 +1,300 @@ +//! The generated standard-14 tables: the fourteen base font names and their per-code advance +//! widths. **Data only, no logic** -- see `std14.rs` for everything that interprets it. +//! +//! This file is the closed-list item in AGENTS.md 1.1 and carries a SHA-256 in `ATTRIBUTION.toml`, +//! so `cargo xtask assets` fails until a change to it is re-attested. It is kept separate from the +//! code that reads it for exactly that reason: if ordinary edits churned the hash, re-attesting +//! would become reflexive and the check would stop meaning anything. +//! +//! Widths are in thousandths of an em, indexed by character code in each face's own encoding -- +//! WinAnsi for the twelve text faces, and their built-in encodings for Symbol and ZapfDingbats. +//! A zero means the encoding leaves that code undefined. Verified against the published +//! specification by the tests in `std14.rs`, which type the expected values in by hand. + +pub(crate) static BASE_FONTS: [&str; 14] = [ + "Helvetica", + "Helvetica-Bold", + "Helvetica-Oblique", + "Helvetica-BoldOblique", + "Times-Roman", + "Times-Bold", + "Times-Italic", + "Times-BoldItalic", + "Courier", + "Courier-Bold", + "Courier-Oblique", + "Courier-BoldOblique", + "Symbol", + "ZapfDingbats", +]; + +/// Advance widths by code, one row per [`Std14`] variant in declaration order. +#[rustfmt::skip] +pub(crate) static WIDTHS: [[u16; 256]; 14] = [ + // Helvetica + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, + ], + // HelveticaBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, + ], + // HelveticaOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, + ], + // HelveticaBoldOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, + ], + // TimesRoman + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, + 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, + 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, + 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, + 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 0, + 500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0, + 0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722, + 250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333, + 400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444, + 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, + 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500, + 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500, + ], + // TimesBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, + 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, + 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, + 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, + 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 0, + 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 0, 667, 0, + 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 444, 722, + 250, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 333, 747, 333, + 400, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750, 750, 500, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389, 389, 389, + 722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722, 611, 556, + 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500, 556, 500, + ], + // TimesItalic + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, + 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, + 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, + 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, + 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 0, + 500, 0, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 0, 556, 0, + 0, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 0, 389, 556, + 250, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 333, 760, 333, + 400, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750, 750, 500, + 611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, + 722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556, 611, 500, + 500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444, 500, 444, + ], + // TimesBoldItalic + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, + 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, + 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, + 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, + 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 0, + 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 0, 611, 0, + 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 389, 611, + 250, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 333, 747, 333, + 400, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750, 750, 500, + 667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389, 389, 389, + 722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611, 611, 500, + 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444, 500, 444, + ], + // Courier + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierBoldOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // Symbol + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, + 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, + 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, + 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, + 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, + 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, + 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, + 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, + 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, + 0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 0, + ], + // ZapfDingbats + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, + 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, + 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, + 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, + 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, + 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 0, + 390, 390, 317, 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, + 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, + 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, + 0, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, 0, + ], +]; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 3e85d8a5b..1652127c5 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -36,6 +36,9 @@ pub mod write_raster; /// Low-level, direct-to-output framing of new classic-xref PDF files. pub mod classic; +/// PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap helpers, and Standard-14 metrics. +#[cfg(feature = "fonts")] +pub mod fonts; #[cfg(test)] extern crate self as craft_pdf; diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 4c8b708b1..d206caaa9 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -52,6 +52,21 @@ pub enum Error { Xml(String), } +/// Errors returned by presentation model editing helpers. +#[derive(Debug, thiserror::Error)] +pub enum ModelError { + #[error("no slide {0}")] + NoSlide(String), + #[error("no shape {0}")] + NoShape(ShapeId), + #[error("no layout {0}")] + NoLayout(LayoutId), + #[error("{0}")] + Invalid(String), +} + +pub type ModelResult = std::result::Result; + /// What the caller supplies where a file or a presentation leaves something out. The reader asks /// for a master when a file has none it can read, and for the theme of a master that names none; /// the writer for a master when the presentation has none, and for the text styles a master or @@ -112,6 +127,12 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta read::import_checked(bytes, defaults) } +/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a +/// table past the cell cap keeps its leading rows). +pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec, Vec), Error> { + read::import_report(bytes, defaults) +} + /// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget /// path without a multi-million-point chart. #[doc(hidden)] @@ -688,6 +709,9 @@ pub struct Slide { pub animations: Vec, /// Speaker notes. pub notes: TextBody, + /// Whether the slide has an associated notes slide even if its text is empty. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub has_notes_slide: bool, pub comments: Vec, /// `clrMapOvr`: a colour map replacing the layout's or master's (`bg1`→`dk1`…); None follows /// the layout. @@ -714,6 +738,7 @@ impl Default for Slide { transition: None, animations: vec![], notes: TextBody::default(), + has_notes_slide: false, comments: vec![], color_map: None, tags: vec![], diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index ffafb2319..588ba1357 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -58,8 +58,13 @@ pub struct Imp<'a> { /// Whether a part has relationships of its own, by normalized part name: looked up once /// however many embedded objects point at the part. pub has_rels: HashMap, + /// Warnings for content cut to fit a limit during import. + pub warnings: Vec, } +/// Import warnings kept; a hostile file with many oversized tables adds no more than this. +const MAX_IMPORT_WARNINGS: usize = 32; + impl<'a> Imp<'a> { fn new(pkg: &'a Package, defaults: &'a dyn Defaults, next: u32, chart_points_cap: usize) -> Self { Imp { @@ -82,6 +87,14 @@ impl<'a> Imp<'a> { tag_bytes: 0, tags_capped: false, has_rels: HashMap::new(), + warnings: vec![], + } + } + /// Record something the file lost, and log it. + pub fn warn(&mut self, msg: String) { + log::warn!("pptx: {msg}"); + if self.warnings.len() < MAX_IMPORT_WARNINGS { + self.warnings.push(msg); } } pub fn alloc(&mut self) -> u32 { @@ -392,11 +405,26 @@ pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result Result<(Presentation, Vec), Error> { - import_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS) + import_report(bytes, defaults).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a +/// table past the cell cap keeps its leading rows). +pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec, Vec), Error> { + import_report_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS) } /// [`import_checked`] with the presentation's chart point budget set (tests lower it). pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, chart_points_cap: usize) -> Result<(Presentation, Vec), Error> { + import_report_with_chart_points(bytes, defaults, chart_points_cap).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_report`] with the presentation's chart point budget set. +fn import_report_with_chart_points( + bytes: &[u8], + defaults: &dyn Defaults, + chart_points_cap: usize, +) -> Result<(Presentation, Vec, Vec), Error> { let mut lost_slides: Vec = vec![]; let pkg = Package::open(bytes)?; let root_rels = pkg.rels(""); @@ -438,7 +466,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, ch p.media = std::mem::take(&mut imp.media); p.next_id = imp.next; p.fix_next_id(); - Ok((p, lost_slides)) + Ok((p, lost_slides, imp.warnings)) } /// Masters, layouts and slides to read, in file order and without duplicates: (master paths, @@ -602,6 +630,7 @@ fn read_slides( let mut slide = read_slide(imp, &part, doc, *id, layout); if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) { slide.notes = notes; + slide.has_notes_slide = true; } read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts); file_slide_ids.insert(*file_id, *id); diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 8e20a5545..3ebaddb99 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -805,6 +805,9 @@ fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table { let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0); t.cols = vec![72.0; n]; } + if t.over_cap() { + imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, craft_drawingml::table::MAX_CELLS)); + } t.normalize(); t } diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 0e8d01b13..30c0b83df 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -458,7 +458,7 @@ struct NotesMasterWrite { fn notes_master_write(p: &Presentation) -> Option { let nm = p.notes_master.as_deref(); let kept = nm.filter(|m| !m.shapes.is_empty()); - let has_notes = p.slides.iter().any(|s| !s.notes.is_empty()); + let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide); if !has_notes && nm.is_none() { return None; } @@ -694,7 +694,7 @@ pub fn export(p: &Presentation, defaults: &dyn Defaults, main_ct: &str) -> Resul if let Some(lp) = layout_parts.get(&s.layout) { so.rels.add("slideLayout", &craft_opc::relative(&sname, lp), false); } - if !s.notes.is_empty() { + if !s.notes.is_empty() || s.has_notes_slide { let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1); so.rels.add("notesSlide", &craft_opc::relative(&sname, &nname), false); let mut no = Out::new(&nname); @@ -1360,7 +1360,7 @@ fn app_xml(p: &Presentation, application: &str) -> Vec { .open(); w.leaf("Application", &[], application); w.leaf("Slides", &[], &p.slides.len().to_string()); - w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty()).count().to_string()); + w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string()); w.leaf("HiddenSlides", &[], &p.slides.iter().filter(|s| s.hidden).count().to_string()); if !p.props.company.is_empty() { w.leaf("Company", &[], &p.props.company); diff --git a/crates/ps/src/read/lex.rs b/crates/ps/src/read/lex.rs new file mode 100644 index 000000000..c8f81add7 --- /dev/null +++ b/crates/ps/src/read/lex.rs @@ -0,0 +1,432 @@ +//! PostScript token scanner over an in-memory byte slice, tracking the unread whitespace +//! boundary for `currentfile` data reads (`read`, `readstring`, filters, `token`, `eexec`). + +use std::fmt; + +/// Deepest procedure nesting the scanner reads. +const MAX_NESTING: usize = 256; + +/// Most bytes an ASCII85 string literal may decode to. +const MAX_ASCII85: usize = 1 << 28; + +/// How an immediately evaluated name (`//name`) is prefixed in [`Token::Exec`], until the +/// interpreter replaces it. +pub const IMMEDIATE: &str = "//"; + +/// A scanned PostScript token. +#[derive(Clone, Debug, PartialEq)] +pub enum Token { + Int(i64), + Real(f64), + /// A literal name (`/name`). + Name(String), + /// An executable name (operator, `[`, `]`, `<<`, `>>`, or `//name` prefixed with [`IMMEDIATE`]). + Exec(String), + /// A byte string (`(...)`, `<...>`, or `<~...~>`). + Str(Vec), + /// A procedure (`{ ... }`). + Proc(Vec), +} + +/// A finite number parsed from a PostScript numeric token. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Number { + Int(i64), + Real(f64), +} + +/// An error returned by [`Lexer::next`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LexError { + Syntax(String), + Limit(&'static str), +} + +impl fmt::Display for LexError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Syntax(what) => write!(f, "syntaxerror: {what}"), + Self::Limit(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for LexError {} + +/// PostScript byte-slice scanner with `currentfile` data boundary tracking. +pub struct Lexer<'a> { + src: &'a [u8], + pos: usize, + /// The whitespace character that ended the last token is still unread (data the program + /// reads from itself starts after it). + fresh: bool, + /// The last object read has immediately evaluated names (`//name`) in it, read as executable + /// names starting with [`IMMEDIATE`] for the interpreter to replace by their values. + pub immediate: bool, +} + +/// Whether `b` is PostScript whitespace. +pub fn is_space(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') +} + +/// Whether `b` is a PostScript delimiter. +pub fn is_delim(b: u8) -> bool { + matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +fn syntax(what: &str) -> Result { + Err(LexError::Syntax(what.to_string())) +} + +impl<'a> Lexer<'a> { + /// Create a scanner over `src`. + pub fn new(src: &'a [u8]) -> Self { + Self { src, pos: 0, fresh: false, immediate: false } + } + + /// What is left to read. + pub fn rest(&self) -> &'a [u8] { + self.src.get(self.pos..).unwrap_or_default() + } + + /// What is left to read as data: after the whitespace that ended the last token (a CR LF + /// pair counts as one). + pub fn data(&mut self) -> &'a [u8] { + if std::mem::take(&mut self.fresh) { + match self.peek() { + Some(b'\r') => { + self.pos += 1; + if self.peek() == Some(b'\n') { + self.pos += 1; + } + } + Some(b) if is_space(b) => self.pos += 1, + _ => {} + } + } + self.rest() + } + + /// Skip `n` bytes (the data a filter or `readstring` took). + pub fn advance(&mut self, n: usize) { + self.fresh = false; + self.pos = self.pos.saturating_add(n).min(self.src.len()); + } + + fn peek(&self) -> Option { + self.src.get(self.pos).copied() + } + + fn skip_space(&mut self) { + while let Some(b) = self.peek() { + if is_space(b) { + self.pos += 1; + } else if b == b'%' { + while let Some(c) = self.peek() { + if c == b'\n' || c == b'\r' { + break; + } + self.pos += 1; + } + } else { + break; + } + } + } + + /// The next token at the top level (`None` at the end of the file). + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> Result, LexError> { + self.immediate = false; + let t = self.token(0)?; + self.fresh = true; + Ok(t) + } + + fn token(&mut self, depth: usize) -> Result, LexError> { + self.skip_space(); + let Some(b) = self.peek() else { return Ok(None) }; + self.pos += 1; + Ok(Some(match b { + b'(' => Token::Str(self.string()?), + b'<' => self.angle_string()?, + b'>' => { + if self.peek() != Some(b'>') { + return syntax(">"); + } + self.pos += 1; + Token::Exec(">>".to_string()) + } + b'[' => Token::Exec("[".to_string()), + b']' => Token::Exec("]".to_string()), + b'{' => self.proc(depth)?, + b'}' | b')' => return syntax(&char::from(b).to_string()), + b'/' => self.name(), + _ => { + self.pos -= 1; + let w = self.word(); + match number(&w) { + Some(Number::Int(i)) => Token::Int(i), + Some(Number::Real(r)) => Token::Real(r), + None => Token::Exec(w), + } + } + })) + } + + fn angle_string(&mut self) -> Result { + match self.peek() { + Some(b'<') => { + self.pos += 1; + Ok(Token::Exec("<<".to_string())) + } + Some(b'~') => { + self.pos += 1; + Ok(Token::Str(self.ascii85()?)) + } + _ => Ok(Token::Str(self.hex()?)), + } + } + + fn proc(&mut self, depth: usize) -> Result { + if depth >= MAX_NESTING { + return Err(LexError::Limit("procedures nested too deeply")); + } + let mut items = vec![]; + loop { + self.skip_space(); + match self.peek() { + None => return syntax("{"), + Some(b'}') => { + self.pos += 1; + break; + } + _ => match self.token(depth + 1)? { + Some(o) => items.push(o), + None => return syntax("{"), + }, + } + } + Ok(Token::Proc(items)) + } + + fn name(&mut self) -> Token { + // `//name` stands for the name's value when it is read. + let immediate = self.peek() == Some(b'/'); + if immediate { + self.pos += 1; + self.immediate = true; + } + let name = self.word(); + if immediate { Token::Exec(format!("{IMMEDIATE}{name}")) } else { Token::Name(name) } + } + + /// A regular token's characters. + fn word(&mut self) -> String { + let start = self.pos; + while let Some(b) = self.peek() { + if is_space(b) || is_delim(b) { + break; + } + self.pos += 1; + } + String::from_utf8_lossy(self.src.get(start..self.pos).unwrap_or_default()).into_owned() + } + + /// A literal string after its `(`. + fn string(&mut self) -> Result, LexError> { + let mut out = vec![]; + let mut depth = 0usize; + loop { + let Some(b) = self.peek() else { return syntax("(") }; + self.pos += 1; + match b { + b'(' => { + depth += 1; + out.push(b); + } + b')' if depth == 0 => return Ok(out), + b')' => { + depth -= 1; + out.push(b); + } + b'\\' => self.string_escape(&mut out)?, + _ => out.push(b), + } + } + } + + fn string_escape(&mut self, out: &mut Vec) -> Result<(), LexError> { + let Some(e) = self.peek() else { return syntax("(") }; + self.pos += 1; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + } + b'\n' => {} + b'0'..=b'7' => { + let mut v = u32::from(e - b'0'); + for _ in 0..2 { + match self.peek() { + Some(d @ b'0'..=b'7') => { + v = v * 8 + u32::from(d - b'0'); + self.pos += 1; + } + _ => break, + } + } + out.push((v & 0xff) as u8); + } + other => out.push(other), + } + Ok(()) + } + + /// A hexadecimal string after its `<`. + fn hex(&mut self) -> Result, LexError> { + let Some(end) = self.rest().iter().position(|b| *b == b'>') else { + return syntax("<"); + }; + let body = self.rest().get(..end).unwrap_or_default(); + let Some(out) = hex_decode(body) else { + return syntax("<"); + }; + self.advance(end + 1); + Ok(out) + } + + /// An ASCII85 string after its `<~`. + fn ascii85(&mut self) -> Result, LexError> { + let Some(end) = find(self.rest(), b"~>") else { + return syntax("<~"); + }; + let text = String::from_utf8_lossy(self.rest().get(..end + 2).unwrap_or_default()).into_owned(); + self.advance(end + 2); + let Some(out) = craft_eps::ascii85::decode(text.as_bytes(), MAX_ASCII85) else { + return syntax("<~"); + }; + Ok(out) + } +} + +/// Where `needle` first starts in `hay`. +pub fn find(hay: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() { + return Some(0); + } + hay.windows(needle.len()).position(|w| w == needle) +} + +/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others. +pub fn hex_decode(body: &[u8]) -> Option> { + let mut out = Vec::with_capacity(body.len() / 2); + let mut high: Option = None; + for &b in body { + if is_space(b) { + continue; + } + let v = char::from(b).to_digit(16)? as u8; + match high.take() { + Some(h) => out.push(h << 4 | v), + None => high = Some(v), + } + } + if let Some(h) = high { + out.push(h << 4); + } + Some(out) +} + +/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`. +pub fn number(w: &str) -> Option { + let first = w.bytes().next()?; + if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { + return None; + } + if let Ok(i) = w.parse::() { + return Some(Number::Int(i)); + } + if let Some((base, digits)) = w.split_once('#') { + let base: u32 = base.parse().ok().filter(|b| (2..=36).contains(b))?; + // `from_str_radix` accepts a leading sign; a PostScript radix number has digits only. + if digits.starts_with(['+', '-']) { + return None; + } + return i64::from_str_radix(digits, base).ok().map(Number::Int); + } + // Rust reads `inf` and `nan`; PostScript doesn't. + if w.bytes().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) { + return None; + } + let v: f64 = w.parse().ok()?; + v.is_finite().then_some(Number::Real(v)) +} + +#[cfg(test)] +mod tests { + use super::{LexError, Lexer, Number, Token, find, hex_decode, number}; + + #[test] + fn radix_number_with_sign_after_hash_is_not_a_number() { + assert!(number("16#+ff").is_none()); + assert!(number("16#-ff").is_none()); + assert_eq!(number("16#ff"), Some(Number::Int(255))); + } + + #[test] + fn currentfile_data_consumes_single_whitespace_or_crlf() { + let mut lex = Lexer::new(b"image\r\nDATA"); + assert_eq!(lex.next(), Ok(Some(Token::Exec("image".into())))); + assert_eq!(lex.rest(), b"\r\nDATA"); + assert_eq!(lex.data(), b"DATA"); + lex.advance(2); + assert_eq!(lex.rest(), b"TA"); + } + + #[test] + fn partial_lines_and_eof() { + let mut lex = Lexer::new(b"1 2 add"); + assert_eq!(lex.next(), Ok(Some(Token::Int(1)))); + assert_eq!(lex.next(), Ok(Some(Token::Int(2)))); + assert_eq!(lex.next(), Ok(Some(Token::Exec("add".into())))); + assert_eq!(lex.next(), Ok(None)); + assert_eq!(lex.data(), b""); + } + + #[test] + fn immediate_names_and_procedures() { + let mut lex = Lexer::new(b"{ //foo /bar }"); + assert_eq!(lex.next(), Ok(Some(Token::Proc(vec![Token::Exec("//foo".into()), Token::Name("bar".into())])))); + assert!(lex.immediate); + } + + #[test] + fn find_and_hex_decode() { + assert_eq!(find(b"abcdef", b"cd"), Some(2)); + assert_eq!(find(b"abcdef", b""), Some(0)); + assert_eq!(find(b"abcdef", b"xy"), None); + assert_eq!(hex_decode(b"41 4"), Some(vec![0x41, 0x40])); + assert_eq!(hex_decode(b"4g"), None); + } + + #[test] + fn unterminated_string_is_syntax_error() { + let mut lex = Lexer::new(b"(open"); + assert_eq!(lex.next(), Err(LexError::Syntax("(".into()))); + } + + #[test] + fn error_does_not_mark_fresh() { + let mut lex = Lexer::new(b") rest"); + assert_eq!(lex.next(), Err(LexError::Syntax(")".into()))); + assert_eq!(lex.data(), b" rest"); + } +} diff --git a/crates/ps/src/read/mod.rs b/crates/ps/src/read/mod.rs index 0fcc3b363..2165547d7 100644 --- a/crates/ps/src/read/mod.rs +++ b/crates/ps/src/read/mod.rs @@ -18,6 +18,7 @@ mod encodings; mod font; mod gstate; mod interp; +pub mod lex; mod obj; mod ops; mod pdf; diff --git a/crates/psd/src/channel_resources.rs b/crates/psd/src/channel_resources.rs index 204d36eb0..2dc77b454 100644 --- a/crates/psd/src/channel_resources.rs +++ b/crates/psd/src/channel_resources.rs @@ -68,6 +68,19 @@ pub fn alternate_spot_colors(data: &[u8]) -> impl ExactSizeIterator(names: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for name in names { + let legacy = crate::io::encode_legacy_name(name); + crate::io::write_pascal(&mut out, &legacy, 1); + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -108,4 +121,10 @@ mod tests { bytes[2..4].copy_from_slice(&0u16.to_be_bytes()); assert_eq!(alternate_spot_colors(&bytes).len(), 0); } + + #[test] + fn pascal_names_encodes_unpadded_legacy_strings() { + assert_eq!(pascal_names(["Spot Color 1"]), b"\x0cSpot Color 1"); + assert_eq!(pascal_names(["café", "A\nB"]), b"\x04caf?\x03A?B"); + } } diff --git a/crates/psd/src/merged.rs b/crates/psd/src/merged.rs index 467fb8904..4741d738c 100644 --- a/crates/psd/src/merged.rs +++ b/crates/psd/src/merged.rs @@ -1,5 +1,8 @@ //! Borrowed, merged-only PSD reader that skips layer records and decodes selected planes. -use crate::{Head, PsdError, Result}; +use crate::{Head, HeadView, PsdError, Result}; + +mod rows; +pub use rows::{ChannelRows, EncodedRow, EncodedRows}; /// Dimensions in the fixed header fields, for reporting a preflight limit error. /// This does not validate the PSD signature or remaining header. @@ -40,17 +43,83 @@ fn u64_at(bytes: &[u8], at: &mut usize) -> Result { Ok(u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])) } +fn has_merged_transparency(layer: &[u8], version: crate::Version) -> bool { + let mut at = 0usize; + let info_len = if version.is_psb() { u64_at(layer, &mut at).ok() } else { u32_at(layer, &mut at).ok().map(u64::from) }; + let Some(info_len) = info_len else { return false }; + if info_len >= 2 { + return layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0); + } + let Ok(info_len) = usize::try_from(info_len) else { return false }; + let Some(next) = at.checked_add(info_len) else { return false }; + at = next; + let Ok(mask_len) = u32_at(layer, &mut at) else { return false }; + let Some(next) = at.checked_add(mask_len as usize) else { return false }; + at = next; + while let Some(head) = at.checked_add(12).and_then(|end| layer.get(at..end)) { + let sig = &head[..4]; + let key = &head[4..8]; + if sig != b"8BIM" && sig != b"8B64" { + return false; + } + let Ok(key_arr): std::result::Result<&[u8; 4], _> = key.try_into() else { return false }; + let len = if crate::tagged::uses_long_length(version, key_arr) { + let Ok(l) = u64_at(layer, &mut { at + 8 }) else { return false }; + let Ok(l) = usize::try_from(l) else { return false }; + at += 16; + l + } else { + at += 12; + u32::from_be_bytes([head[8], head[9], head[10], head[11]]) as usize + }; + if (key == b"Lr16" || key == b"Lr32") && layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0) { + return true; + } + if matches!(key, b"Mtrn" | b"MTrn" | b"Mt16" | b"Mt32") { + return true; + } + // Global tagged blocks pad their data to 4 bytes (per psd-tools and craft-psd). + let Some(next) = len.checked_add(3).map(|v| v & !3).and_then(|p| at.checked_add(p)) else { return false }; + at = next; + } + false +} + impl<'a> Merged<'a> { /// Open the merged section with a pixel limit. This skips layer records, preserving the ability /// to read a composite when its layer data is not understood. No image planes are allocated. pub fn open(bytes: &'a [u8], max_pixels: u64) -> Result { + Self::check_pixel_limit(bytes, max_pixels)?; + Self::from_head(bytes, Head::from_bytes(bytes)?, max_pixels) + } + + /// Open the merged section while omitting all image resources, including valid records. + /// + /// This validates the header and declared section boundaries but skips the resource records. + /// Callers choose when to use it, for example after detecting damaged resources during a strict + /// open. The returned reader borrows the original file and only copies its color-mode data; + /// no resource payloads or image planes are allocated. + pub fn open_without_resources(bytes: &'a [u8], max_pixels: u64) -> Result { + Self::check_pixel_limit(bytes, max_pixels)?; + let view = HeadView::from_bytes(bytes)?; + let mut color_mode_data = Vec::new(); + color_mode_data.try_reserve_exact(view.color_mode_data.len()).map_err(|_| PsdError::OutOfMemory("color-mode data"))?; + color_mode_data.extend_from_slice(view.color_mode_data); + let head = Head { header: view.header, color_mode_data, resources: Vec::new(), layer_section_offset: view.layer_section_offset }; + Self::from_head(bytes, head, max_pixels) + } + + fn check_pixel_limit(bytes: &[u8], max_pixels: u64) -> Result<()> { // Refuse a declared oversized canvas before copying color-mode data or resources. if let Some((w, h)) = declared_dimensions(bytes) && u64::from(w) * u64::from(h) > max_pixels { return Err(PsdError::LimitExceeded("pixel count")); } - let head = Head::from_bytes(bytes)?; + Ok(()) + } + + fn from_head(bytes: &'a [u8], head: Head, max_pixels: u64) -> Result { let h = &head.header; if u64::from(h.width) * u64::from(h.height) > max_pixels { return Err(PsdError::LimitExceeded("pixel count")); @@ -59,8 +128,7 @@ impl<'a> Merged<'a> { let mut at = usize::try_from(head.layer_section_offset).map_err(|_| PsdError::LimitExceeded("offset"))?; let len = if psb { u64_at(bytes, &mut at)? } else { u64::from(u32_at(bytes, &mut at)?) }; let layer = take(bytes, &mut at, usize::try_from(len).map_err(|_| PsdError::LimitExceeded("layer section"))?)?; - let offset = if psb { 8 } else { 4 }; - let transparency = layer.get(offset..offset + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0); + let transparency = has_merged_transparency(layer, h.version); let compression = u16_at(bytes, &mut at)?; Ok(Self { head, transparency, compression, bytes, data_offset: at }) } @@ -248,4 +316,181 @@ mod tests { assert_eq!(row, [7, 8, 0, 0]); assert!(unpackbits(&[0x81, 1], &mut row).is_err()); } + + #[test] + fn detects_lr16_and_mt16_merged_transparency() { + let with_layer = |layer: &[u8]| { + let mut b = head(2, 0); + b.splice(34..38, (layer.len() as u32).to_be_bytes().iter().copied().chain(layer.iter().copied())); + b + }; + let mut lr16 = Vec::new(); + lr16.extend_from_slice(&0u32.to_be_bytes()); + lr16.extend_from_slice(&0u32.to_be_bytes()); + lr16.extend_from_slice(b"8BIMPatt"); + lr16.extend_from_slice(&6u32.to_be_bytes()); + lr16.extend_from_slice(&[1, 2, 3, 4, 5, 6, 0, 0]); + lr16.extend_from_slice(b"8BIMLr16"); + lr16.extend_from_slice(&2u32.to_be_bytes()); + lr16.extend_from_slice(&(-1i16).to_be_bytes()); + assert!(Merged::open(&with_layer(&lr16), 4).unwrap().transparency); + + let n = lr16.len(); + lr16[n - 2..].copy_from_slice(&1i16.to_be_bytes()); + assert!(!Merged::open(&with_layer(&lr16), 4).unwrap().transparency); + + let mut mt16 = vec![0; 8]; + mt16.extend_from_slice(b"8BIMMt16\0\0\0\0"); + assert!(Merged::open(&with_layer(&mt16), 4).unwrap().transparency); + } + + #[test] + fn resource_skipping_open_reads_psd_raw_and_psb_packbits_from_original_bytes() { + for (version, compression) in [(1, 0), (2, 1)] { + let valid_resources = recovery_resource(); + let mut damaged_resources = valid_resources.clone(); + damaged_resources.extend_from_slice(b"BAD!"); + let (bytes, data_offset) = recovery_file(version, compression, &damaged_resources); + let (control_bytes, _) = recovery_file(version, compression, &[]); + let control = Merged::open(&control_bytes, 4).unwrap(); + + assert!(Head::from_bytes(&bytes).is_err()); + assert!(Merged::open(&bytes, 4).is_err()); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert!(std::ptr::eq(recovered.bytes, bytes.as_slice())); + assert_eq!(recovered.data_offset, data_offset); + assert_eq!(recovered.head.header, control.head.header); + assert_eq!(recovered.head.color_mode_data, [9, 8]); + assert!(recovered.head.resources.is_empty()); + assert_eq!(recovered.compression, compression); + assert!(recovered.transparency); + assert_eq!(recovered.transparency, control.transparency); + assert_eq!(recovered.read_planes(2).unwrap(), vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]); + assert_eq!(recovered.read_planes(2).unwrap(), control.read_planes(2).unwrap()); + recovered.validate_all().unwrap(); + + let (valid_bytes, _) = recovery_file(version, compression, &valid_resources); + let strict = Merged::open(&valid_bytes, 4).unwrap(); + assert_eq!(strict.head.resources.len(), 1); + assert_eq!(strict.head.resources[0].id, 1039); + assert_eq!(strict.head.resources[0].data, [7, 6]); + let skipped = Merged::open_without_resources(&valid_bytes, 4).unwrap(); + assert!(skipped.head.resources.is_empty()); + assert_eq!(skipped.read_planes(2).unwrap(), strict.read_planes(2).unwrap()); + } + } + + #[test] + fn resource_skipping_open_ignores_truncated_resource_payload() { + for version in [1, 2] { + let mut resources = recovery_resource(); + resources[8..12].copy_from_slice(&100u32.to_be_bytes()); + let (bytes, _) = recovery_file(version, 0, &resources); + assert!(Merged::open(&bytes, 4).is_err()); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert!(recovered.head.resources.is_empty()); + assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]); + } + } + + #[test] + fn resource_skipping_open_checks_pixel_limit_before_malformed_head() { + let (mut bytes, _) = recovery_file(1, 0, b"BAD!"); + bytes.truncate(22); + bytes[..4].copy_from_slice(b"BAD!"); + assert!(matches!(Merged::open_without_resources(&bytes, 3), Err(PsdError::LimitExceeded("pixel count")))); + assert!(matches!(Merged::open(&bytes, 3), Err(PsdError::LimitExceeded("pixel count")))); + } + + #[test] + fn resource_skipping_open_rejects_out_of_bounds_sections_and_tail_framing() { + for version in [1, 2] { + let (bytes, data_offset) = recovery_file(version, 0, b"BAD!"); + let mut invalid_header = bytes.clone(); + invalid_header[..4].copy_from_slice(b"BAD!"); + assert!(Merged::open_without_resources(&invalid_header, 4).is_err()); + + let mut color_outside_file = bytes.clone(); + color_outside_file[26..30].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(Merged::open_without_resources(&color_outside_file, 4).is_err()); + let mut resources_outside_file = bytes.clone(); + resources_outside_file[32..36].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(Merged::open_without_resources(&resources_outside_file, 4).is_err()); + + let layer_offset = crate::HeadView::from_bytes(&bytes).unwrap().layer_section_offset as usize; + let length_width = if version == 2 { 8 } else { 4 }; + assert!(Merged::open_without_resources(&bytes[..layer_offset + length_width - 1], 4).is_err()); + let mut layer_outside_file = bytes.clone(); + layer_outside_file[layer_offset..layer_offset + length_width].fill(0xff); + assert!(Merged::open_without_resources(&layer_outside_file, 4).is_err()); + assert!(Merged::open_without_resources(&bytes[..data_offset - 1], 4).is_err()); + } + } + + #[test] + fn resource_skipping_open_preserves_selected_plane_and_full_validation_distinction() { + for (version, compression) in [(1, 0), (2, 1)] { + let (mut bytes, _) = recovery_file(version, compression, b"BAD!"); + bytes.truncate(bytes.len() - if compression == 0 { 4 } else { 6 }); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]); + assert!(recovered.read_planes(2).is_err()); + assert!(recovered.validate_all().is_err()); + } + } + + fn recovery_resource() -> Vec { + let mut bytes = b"8BIM".to_vec(); + bytes.extend_from_slice(&1039u16.to_be_bytes()); + bytes.extend_from_slice(&[0, 0]); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&[7, 6]); + bytes + } + + fn recovery_file(version: u16, compression: u16, resources: &[u8]) -> (Vec, usize) { + let mut bytes = b"8BPS".to_vec(); + bytes.extend_from_slice(&version.to_be_bytes()); + bytes.extend_from_slice(&[0; 6]); + bytes.extend_from_slice(&2u16.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&8u16.to_be_bytes()); + bytes.extend_from_slice(&1u16.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&[9, 8]); + bytes.extend_from_slice(&(resources.len() as u32).to_be_bytes()); + bytes.extend_from_slice(resources); + let mut layer = Vec::new(); + if version == 2 { + layer.extend_from_slice(&2u64.to_be_bytes()); + } else { + layer.extend_from_slice(&2u32.to_be_bytes()); + } + layer.extend_from_slice(&(-1i16).to_be_bytes()); + if version == 2 { + bytes.extend_from_slice(&(layer.len() as u64).to_be_bytes()); + } else { + bytes.extend_from_slice(&(layer.len() as u32).to_be_bytes()); + } + bytes.extend_from_slice(&layer); + bytes.extend_from_slice(&compression.to_be_bytes()); + let data_offset = bytes.len(); + if compression == 0 { + bytes.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]); + } else { + for _ in 0..4 { + if version == 2 { + bytes.extend_from_slice(&3u32.to_be_bytes()); + } else { + bytes.extend_from_slice(&3u16.to_be_bytes()); + } + } + for row in [[1, 2], [3, 4], [5, 6], [7, 8]] { + bytes.push(1); + bytes.extend_from_slice(&row); + } + } + (bytes, data_offset) + } } diff --git a/crates/psd/src/merged/rows.rs b/crates/psd/src/merged/rows.rs new file mode 100644 index 000000000..279368b90 --- /dev/null +++ b/crates/psd/src/merged/rows.rs @@ -0,0 +1,284 @@ +//! Allocation-free access to the selected composite channels, one encoded row at a time. + +use super::{Merged, take}; +use crate::{PsdError, Result}; + +/// Validated locations of the first requested composite channels. +/// +/// This view allocates no plane or row index. Unselected channel payloads need not be present. +pub struct EncodedRows<'a> { + table: &'a [u8], + payload: &'a [u8], + entry_bytes: usize, + row_bytes: usize, + height: usize, + used: usize, +} + +/// A sequential cursor over one selected channel, without a decoded plane allocation. +pub struct ChannelRows<'a> { + table: &'a [u8], + payload: &'a [u8], + entry_bytes: usize, + row_bytes: usize, + remaining: usize, +} + +/// A borrowed raw or PackBits row with its declared decoded length. +pub struct EncodedRow<'a> { + bytes: &'a [u8], + row_bytes: usize, + rle: bool, +} + +fn row_length(entry: &[u8]) -> Result { + match *entry { + [a, b] => Ok(usize::from(u16::from_be_bytes([a, b]))), + [a, b, c, d] => usize::try_from(u32::from_be_bytes([a, b, c, d])).map_err(|_| PsdError::LimitExceeded("RLE row size")), + _ => Err(PsdError::invalid("RLE row table entry")), + } +} + +impl<'a> Merged<'a> { + /// Borrow the first `used` raw or PackBits channels for row-at-a-time decoding. + /// + /// Checks the full declared row table and the selected payload extents before returning, + /// without allocating. Eight-, sixteen- and thirty-two-bit samples remain big-endian. + /// `max_row_bytes` limits one decoded row. RLE packet contents are checked on decoding; + /// a short or malformed row is an error, not zero-padded recovery. Existing + /// [`read_planes`](Self::read_planes) keeps its tolerant recovery behaviour. + pub fn encoded_rows(&self, used: usize, max_row_bytes: usize) -> Result> { + let h = &self.head.header; + let channels = usize::from(h.channels); + if used > channels { + return Err(PsdError::invalid("too few channels")); + } + let bpc = match h.depth { + 8 => 1usize, + 16 => 2, + 32 => 4, + _ => return Err(PsdError::Unsupported("merged depth".into())), + }; + let width = usize::try_from(h.width).map_err(|_| PsdError::LimitExceeded("row size"))?; + let height = usize::try_from(h.height).map_err(|_| PsdError::LimitExceeded("row count"))?; + let row_bytes = width.checked_mul(bpc).ok_or(PsdError::LimitExceeded("row size"))?; + if row_bytes > max_row_bytes || row_bytes as u64 > crate::compression::MAX_DECODED_BYTES { + return Err(PsdError::LimitExceeded("merged row size")); + } + let mut at = self.data_offset; + let (table, entry_bytes, payload_bytes) = match self.compression { + 0 => { + let len = used.checked_mul(height).and_then(|n| n.checked_mul(row_bytes)).ok_or(PsdError::LimitExceeded("merged data"))?; + (&[][..], 0, len) + } + 1 => { + let entry = if h.version.is_psb() { 4 } else { 2 }; + // Even when only the first channel is requested, every declared row-length + // entry precedes the payload. Skipping only selected entries reads table bytes. + let table_len = channels.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?; + let full_table = take(self.bytes, &mut at, table_len)?; + let selected_len = used.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?; + let table = full_table.get(..selected_len).ok_or_else(|| PsdError::invalid("row table"))?; + let minimum = row_bytes.div_ceil(128).checked_mul(2).ok_or(PsdError::LimitExceeded("row size"))?; + let mut total = 0usize; + for entry in table.chunks_exact(entry) { + let len = row_length(entry)?; + // Reject impossible expansion before callers allocate the final image. + if len < minimum { + return Err(PsdError::invalid("RLE row too short for its width")); + } + total = total.checked_add(len).ok_or(PsdError::LimitExceeded("merged data"))?; + } + (table, entry, total) + } + _ => return Err(PsdError::Unsupported("merged compression".into())), + }; + let payload = take(self.bytes, &mut at, payload_bytes)?; + Ok(EncodedRows { table, payload, entry_bytes, row_bytes, height, used }) + } +} + +impl<'a> EncodedRows<'a> { + /// Number of decoded bytes in each row. + pub fn row_bytes(&self) -> usize { + self.row_bytes + } + + /// Cursor for a selected channel. RLE setup scans preceding row lengths, without allocating. + pub fn channel(&self, channel: usize) -> Result> { + if channel >= self.used { + return Err(PsdError::invalid("channel was not selected")); + } + let first = channel.checked_mul(self.height).ok_or(PsdError::LimitExceeded("row count"))?; + let (table, offset) = if self.entry_bytes == 0 { + (&[][..], first.checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("channel offset"))?) + } else { + let start = first.checked_mul(self.entry_bytes).ok_or(PsdError::LimitExceeded("row table"))?; + let before = self.table.get(..start).ok_or_else(|| PsdError::invalid("row table"))?; + let mut offset = 0usize; + for entry in before.chunks_exact(self.entry_bytes) { + offset = offset.checked_add(row_length(entry)?).ok_or(PsdError::LimitExceeded("channel offset"))?; + } + (self.table.get(start..).ok_or_else(|| PsdError::invalid("row table"))?, offset) + }; + let payload = self.payload.get(offset..).ok_or_else(|| PsdError::invalid("channel offset"))?; + Ok(ChannelRows { table, payload, entry_bytes: self.entry_bytes, row_bytes: self.row_bytes, remaining: self.height }) + } +} + +impl<'a> ChannelRows<'a> { + /// Read the next encoded row, or `None` after the declared channel height. + pub fn next_row(&mut self) -> Result>> { + if self.remaining == 0 { + return Ok(None); + } + let len = if self.entry_bytes == 0 { + self.row_bytes + } else { + let entry = self.table.get(..self.entry_bytes).ok_or_else(|| PsdError::invalid("row table"))?; + row_length(entry)? + }; + let bytes = self.payload.get(..len).ok_or_else(|| PsdError::invalid("truncated row"))?; + self.payload = self.payload.get(len..).ok_or_else(|| PsdError::invalid("truncated row"))?; + if self.entry_bytes != 0 { + self.table = self.table.get(self.entry_bytes..).ok_or_else(|| PsdError::invalid("row table"))?; + } + self.remaining -= 1; + Ok(Some(EncodedRow { bytes, row_bytes: self.row_bytes, rle: self.entry_bytes != 0 })) + } +} + +impl EncodedRow<'_> { + /// Decode into exactly one row of caller-owned storage, without allocating. + /// + /// Truncated PackBits packets and underfilled/overfilled rows are errors. Bytes after a + /// complete row remain tolerated, matching [`crate::compression::packbits::decode_to_slice`]. + /// On error, the output may contain a partially decoded prefix. + pub fn decode_to_slice(&self, output: &mut [u8]) -> Result<()> { + if output.len() != self.row_bytes { + return Err(PsdError::invalid("decoded row has wrong length")); + } + if self.rle { + crate::compression::packbits::decode_to_slice(self.bytes, output) + } else { + output.copy_from_slice(self.bytes); + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(psb: bool, depth: u16, channels: u16, height: u32, compression: u16) -> Vec { + let mut b = b"8BPS".to_vec(); + b.extend_from_slice(&(if psb { 2u16 } else { 1 }).to_be_bytes()); + b.extend_from_slice(&[0; 6]); + b.extend_from_slice(&channels.to_be_bytes()); + b.extend_from_slice(&height.to_be_bytes()); + b.extend_from_slice(&2u32.to_be_bytes()); + b.extend_from_slice(&depth.to_be_bytes()); + b.extend_from_slice(&1u16.to_be_bytes()); + b.extend_from_slice(&[0; 8]); + b.extend(std::iter::repeat_n(0, if psb { 8 } else { 4 })); + b.extend_from_slice(&compression.to_be_bytes()); + b + } + + #[test] + fn selected_rows_skip_full_table_and_allow_missing_spot_payload() { + for psb in [false, true] { + for depth in [8, 16, 32] { + let row_bytes = 2 * usize::from(depth / 8); + let mut b = file(psb, depth, 3, 2, 1); + for _ in 0..6 { + if psb { + b.extend_from_slice(&2u32.to_be_bytes()); + } else { + b.extend_from_slice(&2u16.to_be_bytes()); + } + } + for value in 1..=4 { + b.extend_from_slice(&[(1i16 - row_bytes as i16) as u8, value]); + } + let merged = Merged::open(&b, 4).unwrap(); + let rows = merged.encoded_rows(2, row_bytes).unwrap(); + assert_eq!(rows.row_bytes(), row_bytes); + assert!(rows.channel(2).is_err()); + for c in 0..2 { + let mut channel = rows.channel(c).unwrap(); + for y in 0..2 { + let mut out = vec![0; row_bytes]; + channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, vec![(c * 2 + y + 1) as u8; row_bytes]); + } + assert!(channel.next_row().unwrap().is_none()); + } + assert!(merged.encoded_rows(3, row_bytes).is_err()); + assert!(merged.encoded_rows(2, row_bytes - 1).is_err()); + assert!(merged.encoded_rows(4, row_bytes).is_err()); + } + } + } + + #[test] + fn raw_rows_are_borrowed_and_require_exact_output_length() { + let mut b = file(false, 16, 2, 2, 0); + b.extend(0..16); + let merged = Merged::open(&b, 4).unwrap(); + let rows = merged.encoded_rows(2, 4).unwrap(); + let mut channel = rows.channel(1).unwrap(); + let row = channel.next_row().unwrap().unwrap(); + assert!(row.decode_to_slice(&mut [0; 3]).is_err()); + let mut out = [0; 4]; + row.decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [8, 9, 10, 11]); + channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [12, 13, 14, 15]); + assert!(channel.next_row().unwrap().is_none()); + b.pop(); + assert!(Merged::open(&b, 4).unwrap().encoded_rows(2, 4).is_err()); + } + + #[test] + fn strict_rows_reject_short_packets_but_keep_trailing_bytes_and_recovery() { + for encoded in [&[3, 7, 8][..], &[0, 7, 128], &[255, 7, 255], &[252, 7]] { + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&(encoded.len() as u16).to_be_bytes()); + b.extend_from_slice(encoded); + let merged = Merged::open(&b, 2).unwrap(); + let rows = merged.encoded_rows(1, 4).unwrap(); + let row = rows.channel(0).unwrap().next_row().unwrap().unwrap(); + assert!(row.decode_to_slice(&mut [0; 4]).is_err(), "{encoded:?}"); + } + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&3u16.to_be_bytes()); + b.extend_from_slice(&[253, 7, 127]); + let merged = Merged::open(&b, 2).unwrap(); + let rows = merged.encoded_rows(1, 4).unwrap(); + let mut out = [0; 4]; + rows.channel(0).unwrap().next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [7; 4]); + b.truncate(b.len() - 3); + b.extend_from_slice(&[3, 7, 8]); + let merged = Merged::open(&b, 2).unwrap(); + assert_eq!(merged.read_planes(1).unwrap(), vec![vec![7, 8, 0, 0]]); + } + + #[test] + fn rejects_incomplete_table_payload_and_impossible_expansion_before_output() { + let mut b = file(false, 16, 2, 1, 1); + b.extend_from_slice(&2u16.to_be_bytes()); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + b.extend_from_slice(&2u16.to_be_bytes()); + b.extend_from_slice(&[253]); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + b.push(7); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_ok()); + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&1u16.to_be_bytes()); + b.push(128); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + } +} diff --git a/crates/psd/src/path.rs b/crates/psd/src/path.rs index 3520a71d8..abfebe9fd 100644 --- a/crates/psd/src/path.rs +++ b/crates/psd/src/path.rs @@ -252,6 +252,24 @@ impl VectorMaskBlock { } } +/// Extract the raw Pascal-string path name bytes from a Clipping Path Name resource (2999). +/// +/// Returns `None` if the resource is empty or truncated before the declared name length. +pub fn clipping_path_name(data: &[u8]) -> Option<&[u8]> { + let len = usize::from(*data.first()?); + data.get(1..1 + len) +} + +/// Encode a Clipping Path Name resource (2999): legacy Pascal name followed by 16.16 unsigned +/// fixed-point flatness. +pub fn clipping_path_resource(name: &str, flatness: f32) -> Vec { + let legacy = crate::io::encode_legacy_name(name); + let mut out = Vec::with_capacity(1 + legacy.len() + 4); + crate::io::write_pascal(&mut out, &legacy, 1); + out.extend_from_slice(&((flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out +} + #[cfg(test)] mod tests { use super::*; @@ -339,4 +357,13 @@ mod tests { assert_eq!(s.len(), 2); assert_eq!(s[0].knots.len(), 3); } + + #[test] + fn clipping_path_resource_roundtrip_and_truncation() { + let bytes = clipping_path_resource("Outline", 1.5); + assert_eq!(bytes, b"\x07Outline\x00\x01\x80\x00"); + assert_eq!(clipping_path_name(&bytes), Some(b"Outline".as_slice())); + assert_eq!(clipping_path_name(&[]), None); + assert_eq!(clipping_path_name(&[5, b'a', b'b']), None); + } } diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index d0ac3e83f..8eefaf25a 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -8,10 +8,14 @@ use crate::io::{Reader, WriteExt, write_pascal}; pub mod ids { /// Resolution info (`ResolutionInfo` structure). pub const RESOLUTION_INFO: u16 = 1005; + /// Alpha channel names as unpadded Pascal strings. + pub const ALPHA_NAMES: u16 = 1006; /// Target layer index. pub const LAYER_STATE: u16 = 1024; /// Layer group ids (one u16 per layer). pub const LAYER_GROUP_INFO: u16 = 1026; + /// Grid and guides (legacy v1). + pub const GUIDES: u16 = 1032; /// Legacy (Photoshop 4) thumbnail, BGR. pub const THUMBNAIL_PS4: u16 = 1033; /// Thumbnail (JFIF). @@ -20,6 +24,8 @@ pub mod ids { pub const GLOBAL_ANGLE: u16 = 1037; /// ICC profile. pub const ICC_PROFILE: u16 = 1039; + /// Unicode alpha channel names. + pub const UNICODE_ALPHA_NAMES: u16 = 1045; /// Global altitude. pub const GLOBAL_ALTITUDE: u16 = 1049; /// Version info (has real merged data flag). @@ -32,6 +38,14 @@ pub mod ids { pub const TIMELINE_INFO: u16 = 1075; /// Selected layer ids (`u16` count followed by `u32` ids). pub const LAYER_SELECTION_IDS: u16 = 1069; + /// Clipping path name and flatness. + pub const CLIPPING_PATH: u16 = 2999; +} + +/// Encode a name for a legacy Pascal field: printable ASCII up to 255 bytes, with other +/// characters replaced by `?`. +pub fn encode_legacy_name(s: &str) -> Vec { + crate::io::encode_legacy_name(s) } /// One image resource block. diff --git a/crates/psd/src/unicode_names.rs b/crates/psd/src/unicode_names.rs index c4547243b..f4a01829a 100644 --- a/crates/psd/src/unicode_names.rs +++ b/crates/psd/src/unicode_names.rs @@ -24,6 +24,20 @@ pub fn records(mut data: &[u8]) -> impl Iterator { }) } +/// Encode counted NUL-terminated big-endian UTF-16 name records (resource 1045). +pub fn write<'a>(names: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for name in names { + let count = name.encode_utf16().count().saturating_add(1); + let count_u32 = u32::try_from(count).unwrap_or(u32::MAX); + out.extend_from_slice(&count_u32.to_be_bytes()); + for unit in name.encode_utf16().take(count_u32 as usize - 1).chain(std::iter::once(0)) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -51,4 +65,13 @@ mod tests { assert_eq!(records(&first[..end]).count(), 0); } } + + #[test] + fn write_roundtrips_with_nul_terminator() { + let bytes = write(["Alpha 1", "café"]); + let decoded: Vec<_> = records(&bytes).collect(); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0], [0, b'A', 0, b'l', 0, b'p', 0, b'h', 0, b'a', 0, b' ', 0, b'1', 0, 0]); + assert_eq!(decoded[1], [0, b'c', 0, b'a', 0, b'f', 0, 0xe9, 0, 0]); + } } diff --git a/crates/raw/README.md b/crates/raw/README.md index d17dd62d7..d709e7047 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -216,3 +216,59 @@ decode bit-exactly; lossy tiles are made with `jpeg-encoder`, JPEG XL tiles with (tests only). Hostile input: every truncation of each sample, byte mutations across the header, 400 random mutations per property, random TIFF-like, lossless-JPEG, opcode-list and CIFF bytes, and a test per limit. + +## Decoder comparison reports + +The native `decode_report` example records the decoded sensor samples and selected metadata for an +explicit, ordered list of local files. It reads one regular file at a time, accepts at most 512 MiB +of encoded bytes per file, and uses `Limits::default()` for decoding. + +```sh +cargo run --quiet --locked --release -p craft-raw --example decode_report -- fixture-a.dng fixture-b.nef > report.tsv +``` + +Use shell redirection that preserves native stdout bytes. The report is UTF-8 TSV with LF line +endings, a header, and one row per argument, indexed from 1. Schema version 1 has these columns in +this order. + +```text +schema input status format sample_type sample_count sensor_sha256 width height cpp bits cfa active_area crop orientation baseline_exposure_bits +``` + +`format` is a fixed lowercase decoder label, such as `dng` or `cfa_tiff`. `sample_type` is `u16` or +`f32`. `sensor_sha256` hashes the complete decoded sample sequence (`RawImage::data`), encoding +each integer as two little-endian bytes and each float's IEEE 754 bits as four little-endian bytes. +The digest is 64 lowercase hexadecimal digits. It reflects any mapping the decoder has already +applied, such as a DNG `LinearizationTable`, so two stored codes that map to the same value give the +same digest. Shape and metadata have their own columns, so an orientation change +can be distinguished from a sample change. + +`cfa` is `width,height,origin_x,origin_y:pattern`, where the pattern is a comma-separated row-major +sequence. It is empty for images without a CFA. Active area and crop are `x,y,width,height`, with +crop coordinates relative to the active area. Orientation is the Exif integer code, and baseline +exposure is the `f64` bit pattern as 16 lowercase hexadecimal digits. + +Each row's status is `ok`, `read_error`, `input_limit`, `not_raw`, `unsupported`, `corrupt`, +`decode_limit`, or `tiff_error`. `input_limit` means the encoded-byte cap was exceeded. +`decode_limit` covers RAW and TIFF decoder limits. A failed input has empty fields after `status`, +and processing continues. The report contains input ordinals, with paths and free-form diagnostics +omitted. A completed batch exits successfully even when inputs fail. No arguments or a report +write or flush failure produces a nonzero exit and a concise diagnostic on stderr. + +To compare two pinned decoder revisions, use separate clean checkouts and keep the example source, +enabled features, and ordered fixture list identical. If a revision predates the example, copy both +`examples/decode_report/main.rs` and `examples/decode_report/report.rs` at the same relative paths +under that checkout's `crates/raw/` directory. The example uses the crate's existing `sha2` dev +dependency. It builds on `main` from +[`ecee6933`](https://github.com/storytold/craft-libs/commit/ecee693322c27acdbcafed4b57066356404e8378) +(#1171, 2026-11-13) onwards, the first revision whose `Cfa` has `origin_x` and `origin_y`. Older +revisions fail to build it. Build and save one report from each checkout, then compare them. + +```sh +git diff --no-index -- before.tsv after.tsv +``` + +Repeat on the same revision to check deterministic output. Record both decoder revisions, the +example source revision, enabled features, fixture checksums and order with the reports. A diff +exit status of 1 indicates differing reports. Inspect the status, sample digest, shape and metadata +columns to identify the change. diff --git a/crates/raw/examples/decode_report/main.rs b/crates/raw/examples/decode_report/main.rs new file mode 100644 index 000000000..94b722562 --- /dev/null +++ b/crates/raw/examples/decode_report/main.rs @@ -0,0 +1,35 @@ +//! Report the decoded samples and selected metadata of explicitly supplied RAW files. +//! `cargo run --locked -p craft-raw --example decode_report -- [ ...]` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(not(target_arch = "wasm32"))] +mod report; + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + use std::io::{self, Write}; + use std::process::ExitCode; + + let stdout = io::stdout(); + let mut out = stdout.lock(); + match report::run(std::env::args_os().skip(1), &mut out, report::MAX_INPUT_BYTES, &craft_raw::Limits::default()) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + let stderr = io::stderr(); + let mut err = stderr.lock(); + match error { + report::RunError::Usage => { + let _ = writeln!(err, "usage: decode_report [ ...]"); + } + report::RunError::Output(error) => { + let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind()); + } + } + ExitCode::FAILURE + } + } +} + +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/crates/raw/examples/decode_report/report.rs b/crates/raw/examples/decode_report/report.rs new file mode 100644 index 000000000..2d0c14dc0 --- /dev/null +++ b/crates/raw/examples/decode_report/report.rs @@ -0,0 +1,154 @@ +use std::ffi::OsString; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::path::Path; + +use craft_raw::{Limits, RawData, RawError, RawFormat, RawImage, Rect}; +use craft_tiff::TiffError; +use sha2::{Digest, Sha256}; + +pub(super) const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024; +const SCHEMA: u8 = 1; +const HEADER: &str = "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\tactive_area\tcrop\torientation\tbaseline_exposure_bits"; + +#[derive(Debug)] +pub(super) enum RunError { + Usage, + Output(io::Error), +} + +pub(super) fn run(paths: impl IntoIterator, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> { + let mut paths = paths.into_iter().peekable(); + if paths.peek().is_none() { + return Err(RunError::Usage); + } + writeln!(out, "{HEADER}").map_err(RunError::Output)?; + for (index, path) in paths.enumerate() { + let input = index + 1; + let result = read_input(Path::new(&path), max_input_bytes) + .map_err(|failure| match failure { + InputFailure::Read => "read_error", + InputFailure::Limit => "input_limit", + }) + .and_then(|bytes| craft_raw::decode_with(&bytes, limits).map_err(decode_status)); + match result { + Ok(raw) => write_success(out, input, &raw), + Err(status) => write_failure(out, input, status), + } + .map_err(RunError::Output)?; + } + out.flush().map_err(RunError::Output) +} + +enum InputFailure { + Read, + Limit, +} + +fn read_input(path: &Path, max_input_bytes: u64) -> Result, InputFailure> { + // Reject non-regular paths before opening, and check the opened file again. + check_input(&fs::metadata(path).map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let file = File::open(path).map_err(|_| InputFailure::Read)?; + check_input(&file.metadata().map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let mut bytes = Vec::new(); + // A file may grow after the metadata check. Read at most one extra byte to detect it. + file.take(max_input_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|_| InputFailure::Read)?; + if bytes.len() as u64 > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(bytes) +} + +fn check_input(metadata: &fs::Metadata, max_input_bytes: u64) -> Result<(), InputFailure> { + if !metadata.is_file() { + return Err(InputFailure::Read); + } + if metadata.len() > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(()) +} + +fn decode_status(error: RawError) -> &'static str { + match error { + RawError::NotRaw => "not_raw", + RawError::Unsupported(_) => "unsupported", + RawError::Corrupt(_) => "corrupt", + RawError::Limit(_) | RawError::Tiff(TiffError::Limit(_)) => "decode_limit", + RawError::Tiff(_) => "tiff_error", + } +} + +fn write_failure(out: &mut impl Write, input: usize, status: &str) -> io::Result<()> { + // Keep all 13 success-only fields present and empty. + writeln!(out, "{SCHEMA}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t") +} + +fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> { + let mut hash = Sha256::new(); + let (sample_type, count) = match &raw.data { + RawData::U16(samples) => { + for sample in samples { + hash.update(sample.to_le_bytes()); + } + ("u16", samples.len()) + } + RawData::F32(samples) => { + for sample in samples { + hash.update(sample.to_bits().to_le_bytes()); + } + ("f32", samples.len()) + } + }; + let digest = hash.finalize(); + write!( + out, + "{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t", + format_label(raw.format), + raw.width, + raw.height, + raw.cpp, + raw.bits, + )?; + if let Some(cfa) = &raw.cfa { + write!(out, "{},{},{},{}:", cfa.width, cfa.height, cfa.origin_x, cfa.origin_y)?; + let mut pattern = cfa.pattern.iter(); + if let Some(first) = pattern.next() { + write!(out, "{first}")?; + for channel in pattern { + write!(out, ",{channel}")?; + } + } + } + write_rect(out, raw.active_area)?; + write_rect(out, raw.crop)?; + writeln!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits()) +} + +fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> { + write!(out, "\t{},{},{},{}", rect.x, rect.y, rect.width, rect.height) +} + +fn format_label(format: RawFormat) -> &'static str { + match format { + RawFormat::Dng => "dng", + RawFormat::Cr2 => "cr2", + RawFormat::Cr3 => "cr3", + RawFormat::Nef => "nef", + RawFormat::Nrw => "nrw", + RawFormat::Arw => "arw", + RawFormat::Raf => "raf", + RawFormat::Orf => "orf", + RawFormat::Rw2 => "rw2", + RawFormat::Pef => "pef", + RawFormat::Srw => "srw", + RawFormat::Crw => "crw", + RawFormat::Mrw => "mrw", + RawFormat::X3f => "x3f", + RawFormat::CfaTiff => "cfa_tiff", + RawFormat::KodakDcs => "kodak_dcs", + RawFormat::Erf => "erf", + RawFormat::Mef => "mef", + RawFormat::OtherTiff => "other_tiff", + } +} diff --git a/crates/raw/tests/it/decode_report.rs b/crates/raw/tests/it/decode_report.rs new file mode 100644 index 000000000..89c800ce6 --- /dev/null +++ b/crates/raw/tests/it/decode_report.rs @@ -0,0 +1,217 @@ +use super::dng::{base_ifd, dng, synthetic}; +use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng}; +use craft_tiff::{ByteOrder, ImageData, Value, tags}; +use std::ffi::OsString; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +#[path = "../../examples/decode_report/report.rs"] +mod report; + +const HEADER: &str = concat!( + "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\t", + "active_area\tcrop\torientation\tbaseline_exposure_bits\n", +); + +struct FixtureDir(PathBuf); + +impl FixtureDir { + fn new(test: &str) -> Self { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")); + for attempt in 0..1000 { + let path = root.join(format!("decode-report-{test}-{}-{attempt}", std::process::id())); + // Only clean up a directory this test created, even if a process ID was reused. + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("create fixture directory {}: {error}", path.display()), + } + } + panic!("no free fixture directory for {test}"); + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for FixtureDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn integer_raw() -> RawImage { + let mut raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); + raw.data = RawData::U16((256..512).collect()); + raw.color.baseline_exposure = 0.5; + raw +} + +fn float_raw() -> RawImage { + let mut raw = synthetic(16, 16, None, 3); + raw.data = RawData::F32((0..16 * 16 * 3).map(|i| (i % 16) as f32 / 16.0).collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.color.baseline_exposure = 0.5; + raw +} + +fn write_fixture(dir: &Path, name: &str, raw: &RawImage, order: ByteOrder) -> OsString { + let bytes = write_dng(raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, ..Default::default() }).unwrap(); + write_bytes(dir, name, &bytes) +} + +fn write_bytes(dir: &Path, name: &str, bytes: &[u8]) -> OsString { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.into_os_string() +} + +fn run_report(paths: &[OsString], max_input_bytes: u64, limits: &Limits) -> Vec { + let mut output = Vec::new(); + assert!(report::run(paths.iter().cloned(), &mut output, max_input_bytes, limits).is_ok()); + output +} + +#[test] +fn reports_exact_samples_shape_and_metadata_in_argument_order() { + let fixtures = FixtureDir::new("success"); + let dir = fixtures.path(); + let original = integer_raw(); + let integer = write_fixture(dir, "integer.dng", &original, ByteOrder::Little); + let float = write_fixture(dir, "float.dng", &float_raw(), ByteOrder::Big); + + let mut changed_sample = original.clone(); + let RawData::U16(samples) = &mut changed_sample.data else { + panic!("integer fixture must contain integer samples"); + }; + samples[127] += 1; + let changed_sample = write_fixture(dir, "changed-sample.dng", &changed_sample, ByteOrder::Little); + + let mut rotated = original; + rotated.orientation = Orientation::Normal; + let rotated = write_fixture(dir, "changed-orientation.dng", &rotated, ByteOrder::Little); + + let paths = [integer.clone(), float, changed_sample, rotated, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + // The digests were generated independently from the known little-endian u16 and f32 bytes. + let rows = concat!( + "1\t1\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t2\tok\tdng\tf32\t768\tc50a4d270d6140ad9988fd8002c5b5de4a78b0b8d598b4db1a5a5385bd4119fd\t16\t16\t3\t32\t\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t3\tok\tdng\tu16\t256\t3ebf95a27aa36848dc2fc39f537625913e29fd1d390c41b50a527f27f1d5ce91\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t4\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t1\t3fe0000000000000\n", + "1\t5\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + ); + assert_eq!(String::from_utf8(first).unwrap(), format!("{HEADER}{rows}")); +} + +fn report_rows(text: &str) -> Vec> { + text.strip_prefix(HEADER) + .unwrap() + .lines() + .map(|line| { + let fields: Vec<_> = line.split('\t').collect(); + assert_eq!(fields.len(), 16); + fields + }) + .collect() +} + +#[test] +fn reports_mixed_failures_and_keeps_the_last_success() { + let fixtures = FixtureDir::new("mixed"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let unreadable = dir.join("missing.dng").into_os_string(); + let text = write_bytes(dir, "private-fixture-name.txt", b"not a recognized RAW header"); + + let mut unsupported = base_ifd(8, 6, 16, 2, false); + unsupported.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2 * 2]] }); + let unsupported = write_bytes(dir, "unsupported.dng", &dng(unsupported, ByteOrder::Little)); + + let mut corrupt = base_ifd(8, 6, 16, 1, true); + corrupt.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 2])); + corrupt.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2]] }); + let corrupt = write_bytes(dir, "corrupt.dng", &dng(corrupt, ByteOrder::Little)); + + let missing_strips = dng(base_ifd(8, 6, 16, 1, true), ByteOrder::Little); + let tiff_error = write_bytes(dir, "missing-strips.dng", &missing_strips); + let paths = [integer.clone(), unreadable, text, unsupported, corrupt, tiff_error, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + let text = String::from_utf8(first).unwrap(); + assert!(!text.contains("private-fixture-name")); + assert!(!text.contains("CFAPattern size mismatch")); + let rows = report_rows(&text); + let statuses = ["ok", "read_error", "not_raw", "unsupported", "corrupt", "tiff_error", "ok"]; + assert_eq!(rows.len(), statuses.len()); + for (index, (row, status)) in rows.iter().zip(statuses).enumerate() { + assert_eq!(row[0], "1"); + assert_eq!(row[1], (index + 1).to_string()); + assert_eq!(row[2], status); + if status != "ok" { + assert!(row[3..].iter().all(|field| field.is_empty())); + } + } + assert_eq!(rows[0][2..], rows[6][2..]); +} + +#[test] +fn separates_encoded_file_and_shared_decoder_limits() { + let fixtures = FixtureDir::new("limits"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let size = std::fs::metadata(Path::new(&integer)).unwrap().len(); + let paths = [integer]; + for (max_input_bytes, max_samples, status) in [(size, 256, "ok"), (size - 1, 256, "input_limit"), (size, 255, "decode_limit")] { + let mut limits = Limits::default(); + limits.max_samples = max_samples; + let output = String::from_utf8(run_report(&paths, max_input_bytes, &limits)).unwrap(); + let rows = report_rows(&output); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][..3], ["1", "1", status]); + if status != "ok" { + assert!(rows[0][3..].iter().all(|field| field.is_empty())); + } + } +} + +#[test] +fn empty_arguments_report_usage_without_writing_a_header() { + let mut output = Vec::new(); + let result = report::run([], &mut output, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Usage))); + assert!(output.is_empty()); +} + +struct BrokenOutput { + write_error: bool, +} + +impl Write for BrokenOutput { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.write_error { Err(io::Error::from(io::ErrorKind::BrokenPipe)) } else { Ok(bytes.len()) } + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::from(io::ErrorKind::WriteZero)) + } +} + +#[test] +fn write_and_flush_errors_fail_the_invocation() { + let fixtures = FixtureDir::new("output-error"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + for (write_error, kind) in [(true, io::ErrorKind::BrokenPipe), (false, io::ErrorKind::WriteZero)] { + let mut out = BrokenOutput { write_error }; + let result = report::run([integer.clone()], &mut out, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Output(error)) if error.kind() == kind)); + } +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 21074a828..e4c41b156 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -749,6 +749,7 @@ fn malformed_profile_look_tags_are_ignored() { } /// Lossless JPEG XL codestream of `px` (`w × h × cpp` interleaved), 16-bit unless `eight`. +#[cfg(feature = "jxl")] fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec { use zune_core::bit_depth::BitDepth; use zune_core::colorspace::ColorSpace; @@ -765,6 +766,7 @@ fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec Vec { let mut b = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a, 0, 0, 0, 0x14]; b.extend_from_slice(b"ftypjxl \0\0\0\0jxl "); @@ -777,6 +779,7 @@ fn jxl_container(cs: &[u8]) -> Vec { /// A tiled JPEG XL raw IFD of `px`. Edge tiles alternate between being coded at their in-image size /// and padded to the nominal tile size (with junk the decoder must drop); tiles alternate between bare /// codestreams and containers. +#[cfg(feature = "jxl")] fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, tile: (usize, usize)) -> IfdBuilder { let (tw, th) = tile; let mut tiles = Vec::new(); @@ -804,6 +807,7 @@ fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, t } #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_tiles_decode_bit_exactly() { let (w, h) = (37, 29); // LinearRaw 3 × 16-bit, the full code range @@ -831,6 +835,7 @@ fn jpeg_xl_tiles_decode_bit_exactly() { } #[test] +#[cfg(feature = "jxl")] fn malformed_jpeg_xl_tiles_are_errors() { use craft_raw::RawError; let (w, h) = (16, 16); @@ -868,6 +873,7 @@ fn malformed_jpeg_xl_tiles_are_errors() { /// One undecodable tile makes the whole image an error: it is never returned with a black tile. #[test] +#[cfg(feature = "jxl")] fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() { use craft_raw::RawError; let (w, h) = (32, 16); @@ -890,6 +896,7 @@ fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() { /// about twice what one plane may use, and is an error rather than an allocation the header asks /// for. The same samples without the alpha channel decode. #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() { use craft_raw::RawError; use zune_core::bit_depth::BitDepth; @@ -911,6 +918,7 @@ fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() { } #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_preview_ifd_is_offered() { let raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); let RawData::U16(px) = &raw.data else { unreachable!() }; diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs index 30f331263..a13bdf29f 100644 --- a/crates/raw/tests/it/main.rs +++ b/crates/raw/tests/it/main.rs @@ -1,5 +1,7 @@ //! The integration tests, one module per file, linked into one test binary. +#[cfg(all(feature = "dng", not(target_arch = "wasm32")))] +mod decode_report; #[cfg(feature = "dng")] mod dng; #[cfg(feature = "line-dng")] diff --git a/crates/sqlite/Cargo.toml b/crates/sqlite/Cargo.toml new file mode 100644 index 000000000..45b255b0d --- /dev/null +++ b/crates/sqlite/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-sqlite" +description = "Bounded wire-format helpers for SQLite database readers." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/sqlite/src/lib.rs b/crates/sqlite/src/lib.rs new file mode 100644 index 000000000..a86c4bcbb --- /dev/null +++ b/crates/sqlite/src/lib.rs @@ -0,0 +1,87 @@ +#![no_std] +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! Wire helpers for the [SQLite database file format](https://www.sqlite.org/fileformat.html). +//! +//! The caller owns cursor advancement, field bounds, and interpretation of stored values. + +use core::fmt; + +const MAX_VARINT_BYTES: usize = 9; + +/// A failure to decode part of a SQLite record or page. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + /// Input ended before the integer was complete. + TruncatedVarint, + /// The serial type is reserved and has no defined field width. + ReservedSerialType(u64), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TruncatedVarint => f.write_str("truncated SQLite varint"), + Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"), + } + } +} + +impl core::error::Error for Error {} + +/// Decode the leading SQLite varint and return its raw bit pattern and byte count. +/// +/// The first eight bytes each contribute seven bits. If all eight have the high bit set, +/// the ninth contributes all eight bits. The caller interprets the bits as signed when needed. +/// Decoding ends at the first complete representation, including non-minimal encodings. +/// +/// # Errors +/// +/// Returns [`Error::TruncatedVarint`] if the slice ends before the integer is complete. +/// +/// ``` +/// use craft_sqlite::read_varint; +/// +/// assert_eq!(read_varint(&[0x81, 0x00, 0xff]), Ok((128, 2))); +/// ``` +pub fn read_varint(input: &[u8]) -> Result<(u64, usize), Error> { + let mut value = 0; + for (index, &byte) in input.iter().take(MAX_VARINT_BYTES).enumerate() { + if index == MAX_VARINT_BYTES - 1 { + return Ok(((value << 8) | u64::from(byte), MAX_VARINT_BYTES)); + } + value = (value << 7) | u64::from(byte & 0x7f); + if byte & 0x80 == 0 { + return Ok((value, index + 1)); + } + } + Err(Error::TruncatedVarint) +} + +/// Return the encoded body width in bytes for a SQLite record serial type. +/// +/// The width is independent of the host's pointer size. The caller checks it against the +/// available body bytes before reading a field. +/// +/// # Errors +/// +/// Returns [`Error::ReservedSerialType`] for codes 10 and 11. +/// +/// ``` +/// use craft_sqlite::serial_type_len; +/// +/// assert_eq!(serial_type_len(3), Ok(3)); +/// assert_eq!(serial_type_len(17), Ok(2)); +/// ``` +pub const fn serial_type_len(serial_type: u64) -> Result { + match serial_type { + 0 | 8 | 9 => Ok(0), + 1..=4 => Ok(serial_type), + 5 => Ok(6), + 6 | 7 => Ok(8), + 10 | 11 => Err(Error::ReservedSerialType(serial_type)), + // Integer division accounts for the one-code difference between BLOB and text. + _ => Ok((serial_type - 12) / 2), + } +} diff --git a/crates/sqlite/tests/wire.rs b/crates/sqlite/tests/wire.rs new file mode 100644 index 000000000..9ef7bb278 --- /dev/null +++ b/crates/sqlite/tests/wire.rs @@ -0,0 +1,71 @@ +use craft_sqlite::{Error, read_varint, serial_type_len}; + +#[test] +fn varints_decode_at_each_width() { + let cases: &[(&[u8], u64)] = &[ + (&[0x7f], 127), + (&[0x81, 0], 1 << 7), + (&[0x81, 0x80, 0], 1 << 14), + (&[0x81, 0x80, 0x80, 0], 1 << 21), + (&[0x81, 0x80, 0x80, 0x80, 0], 1 << 28), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0], 1 << 35), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 42), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 49), + (&[0x80, 0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 56), + ]; + for &(bytes, expected) in cases { + assert_eq!(read_varint(bytes), Ok((expected, bytes.len())), "{bytes:x?}"); + } +} + +#[test] +fn ninth_byte_keeps_all_bits_and_leaves_trailing_bytes() { + let bytes = [0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x42]; + assert_eq!(read_varint(&bytes), Ok((0x8000_0000_0000_0080, 9))); + assert_eq!(read_varint(&[0xff; 9]), Ok((u64::MAX, 9))); +} + +#[test] +fn leading_varint_preserves_following_bytes_and_accepts_padding() { + assert_eq!(read_varint(&[0, 0xff]), Ok((0, 1))); + assert_eq!(read_varint(&[0x81, 0, 0xff]), Ok((128, 2))); + assert_eq!(read_varint(&[0x80, 1, 0xff]), Ok((1, 2))); +} + +#[test] +fn varint_refuses_every_incomplete_prefix() { + let bytes = [0xff; 9]; + for len in 0..bytes.len() { + assert_eq!(read_varint(&bytes[..len]), Err(Error::TruncatedVarint), "length {len}"); + } +} + +#[test] +fn fixed_serial_types_have_exact_widths() { + for (serial_type, width) in (0..).zip([0, 1, 2, 3, 4, 6, 8, 8, 0, 0]) { + assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}"); + } +} + +#[test] +fn reserved_serial_types_are_refused() { + for serial_type in [10, 11] { + assert_eq!(serial_type_len(serial_type), Err(Error::ReservedSerialType(serial_type))); + } +} + +#[test] +fn variable_serial_type_widths_are_portable() { + for (serial_type, width) in [ + (12, 0), + (13, 0), + (14, 1), + (15, 1), + (12_012, 6_000), + (12_013, 6_000), + (u64::MAX - 1, 9_223_372_036_854_775_801), + (u64::MAX, 9_223_372_036_854_775_801), + ] { + assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}"); + } +} diff --git a/crates/story-render/src/main.rs b/crates/story-render/src/main.rs index f3214431f..2af9566eb 100644 --- a/crates/story-render/src/main.rs +++ b/crates/story-render/src/main.rs @@ -25,7 +25,7 @@ //! contrast without them). A value that is not one of these is refused. `stories.tsv` lists the scale of every image. use craft_behavior::ColumnWidth; -use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface}; +use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface, Tracked}; use craft_ui::fonts::{I18nScripts, UiFonts}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::commands::CommandInput; @@ -312,7 +312,7 @@ fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options) // The command states of the story shown, as the gallery gives them, before the first frame. The Overview gives its // cards none, so a card is rendered under none. frames.commands(match &job.shown { - Shown::Story(registration) => Story::command_input([®istration.story]), + Shown::Story(registration) => CommandInput::new().states(&Tracked::new(Story::command_states([®istration.story]))), Shown::Card(_) => CommandInput::new(), }); let (shown, dialog) = match &job.shown { diff --git a/crates/svg/README.md b/crates/svg/README.md index a82d88028..d6c0d9545 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -17,6 +17,13 @@ The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent ### Transform compatibility `transform_compat::parse_transform` preserves EffectCraft transform-list recovery and exact composition. It retains six numeric arguments per operation; scanning is not time/byte capped and matrix overflow behavior is unchanged. The strict geometry reader is unchanged. Source: Brandon Thomas, EffectCraft94e1c86d89a866771f80ad1610afda9aa12e85d8; bounded safe argument matching by Altynzhan Karybai,4035d181329e847d7a57bf3d059502ea2c91b560. +### Document and CSS style compatibility + +`doc_style` preserves EffectCraft's presentation-attribute + stylesheet + inline-`style` +cascade, unit/percentage length resolution, `PaintRef`/`resolve_paint`, and +`viewBox`/`preserveAspectRatio` transform helpers while leaving scene-graph mapping +with the importer. Note that `doc_style::length()` treats unknown units as `px` (`_ => v`). + ### Opt-in validated embedded images diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs new file mode 100644 index 000000000..fa830aa6c --- /dev/null +++ b/crates/svg/src/doc_style.rs @@ -0,0 +1,457 @@ +//! Compatibility SVG document/CSS interpretation helpers extracted from EffectCraft. +//! +//! Provides presentation-attribute + stylesheet + inline-`style` declaration collection +//! ([`declared`](crate::doc_style::declared)), property cascading ([`cascade`](crate::doc_style::cascade)), unit/percentage length resolution +//! ([`length`](crate::doc_style::length), [`attr_len`](crate::doc_style::attr_len)), paint reference parsing/resolution ([`PaintRef`](crate::doc_style::PaintRef), [`paint_ref`](crate::doc_style::paint_ref), +//! [`resolve_paint`](crate::doc_style::resolve_paint)), and `viewBox` / `preserveAspectRatio` transforms ([`viewbox`](crate::doc_style::viewbox), +//! [`viewbox_transform`](crate::doc_style::viewbox_transform)). + +use std::collections::HashMap; + +use kurbo::Affine; + +use crate::{ + color::parse_rgba_compat, + prefix_path::numbers_bounded, + simple_css::{StyleSheet, declarations}, +}; + +/// SVG `fill-rule` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FillRule { + #[default] + NonZero, + EvenOdd, +} + +/// SVG `stroke-linecap` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Cap { + #[default] + Butt, + Round, + Square, +} + +/// SVG `stroke-linejoin` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Join { + #[default] + Miter, + Round, + Bevel, +} + +/// Parsed SVG paint reference (`none`, `currentColor`, `url(#id) [fallback]`, or RGBA color). +#[derive(Clone, Debug, PartialEq)] +pub enum PaintRef { + /// Solid straight RGBA color `[r, g, b, a]` in `0.0..=1.0`. + Color([f64; 4]), + /// Paint server reference `url(#id)` with an optional fallback RGBA color. + Url(String, Option<[f64; 4]>), + /// `currentColor`. + Current, +} + +/// Caller outcome when resolving a `url(#id)` paint reference. +#[derive(Clone, Debug, PartialEq)] +pub enum UrlPaint { + /// Resolved to a caller paint server (for example, a gradient or pattern). + Server(S), + /// Resolved to a solid RGBA color (for example, a single-stop gradient). + Color([f64; 4]), + /// No paint server found; fall back to the `url(#id) fallback` color if present. + Fallback, + /// Paint server found but empty or invalid; do not fall back. + None, +} + +/// Result of resolving a [`PaintRef`] without committing to a caller's paint-server type. +#[derive(Clone, Debug, PartialEq)] +pub enum ResolvedPaint { + /// Solid RGB color `[r, g, b]` with alpha `a`. + Color([f64; 3], f64), + /// A caller-resolved paint server (`url(#id)`). + Server(S), +} + +/// Inherited SVG style state. +#[derive(Clone, Debug, PartialEq)] +pub struct Style { + pub fill: Option, + pub fill_opacity: f64, + pub fill_rule: FillRule, + pub stroke: Option, + pub stroke_opacity: f64, + pub stroke_width: f64, + pub cap: Cap, + pub join: Join, + pub miter: f64, + pub dash: Option>, + pub dash_offset: f64, + pub color: [f64; 4], + pub visible: bool, + pub font_size: f64, +} + +impl Default for Style { + fn default() -> Self { + Style { + fill: Some(PaintRef::Color([0.0, 0.0, 0.0, 1.0])), + fill_opacity: 1.0, + fill_rule: FillRule::NonZero, + stroke: None, + stroke_opacity: 1.0, + stroke_width: 1.0, + cap: Cap::Butt, + join: Join::Miter, + miter: 4.0, + dash: None, + dash_offset: 0.0, + color: [0.0, 0.0, 0.0, 1.0], + visible: true, + font_size: 16.0, + } + } +} + +/// Presentation attributes recognised by [`declared`]. +pub const STYLE_PROPS: &[&str] = &[ + "fill", + "fill-opacity", + "fill-rule", + "stroke", + "stroke-width", + "stroke-opacity", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-dasharray", + "stroke-dashoffset", + "opacity", + "display", + "visibility", + "color", + "font-size", + "transform", + "stop-color", + "stop-opacity", +]; + +/// Collect the declared properties of an element: presentation attributes, then CSS rules +/// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute. +pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap { + let mut out = HashMap::new(); + for a in n.attributes() { + if STYLE_PROPS.contains(&a.name()) && a.name() != "transform" { + out.insert(a.name().to_string(), a.value().to_string()); + } + } + css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut out, charge_css); + if let Some(st) = n.attribute("style") { + for (k, v) in declarations(st) { + out.insert(k, v); + } + } + out +} + +/// Parse an SVG length or percentage into user-space pixels. +/// +/// `axis` selects the percentage reference base: `'x'` uses `vw`, `'y'` uses `vh`, and any +/// other value uses the normalized diagonal `((vw^2 + vh^2) / 2).sqrt()`. +pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option { + let s = s.trim(); + let num_end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len()); + // "e" also starts "em"/"ex": back off if the number does not parse. + let (mut num, mut unit) = (&s[..num_end], &s[num_end..]); + if num.parse::().is_err() && (num.ends_with('e') || num.ends_with('E')) { + let back = num_end.saturating_sub(1); + num = &s[..back]; + unit = &s[back..]; + } + let v: f64 = num.parse().ok()?; + let value = match unit.trim() { + "" | "px" => v, + "pt" => v * 4.0 / 3.0, + "pc" => v * 16.0, + "mm" => v * 96.0 / 25.4, + "cm" => v * 96.0 / 2.54, + "in" => v * 96.0, + "em" => v * font, + "ex" => v * font / 2.0, + "%" => { + let base = match axis { + 'x' => vw, + 'y' => vh, + _ => ((vw * vw + vh * vh) / 2.0).sqrt(), + }; + v / 100.0 * base + } + _ => v, + }; + value.is_finite().then_some(value) +} + +/// Parse a length attribute on `n`, returning `0.0` if missing or invalid. +pub fn attr_len(n: roxmltree::Node, name: &str, axis: char, st: &Style, vw: f64, vh: f64) -> f64 { + n.attribute(name).and_then(|v| length(v, axis, st.font_size, vw, vh)).unwrap_or(0.0) +} + +/// Parse an SVG paint value (`none`, `currentColor`, `url(#id) [fallback]`, `inherit`, or color). +/// +/// Returns `None` for `"inherit"` or unrecognized values, `Some(None)` for `"none"`, and +/// `Some(Some(PaintRef))` for concrete paints or `url(...)` / `currentColor` references. +pub fn paint_ref(v: &str) -> Option> { + let v = v.trim(); + if v == "none" { + return Some(None); + } + if v == "currentColor" || v == "currentcolor" { + return Some(Some(PaintRef::Current)); + } + if let Some(rest) = v.strip_prefix("url(") { + let (url, fallback) = rest.split_once(')').unwrap_or((rest, "")); + let url = url.trim().trim_matches(['"', '\'']); + let id = url.strip_prefix('#').filter(|id| !id.is_empty()).unwrap_or_default().to_string(); + let fb = fallback.trim(); + let fb = if fb.is_empty() || fb == "none" { None } else { parse_rgba_compat(fb) }; + return Some(Some(PaintRef::Url(id, fb))); + } + if v == "inherit" { + return None; + } + parse_rgba_compat(v).map(|c| Some(PaintRef::Color(c))) +} + +/// Apply an element's declared inherited properties to `st`. +/// +/// Returns `(opacity, display)` where `display` is `false` when `display: none` is set. +pub fn cascade(n: roxmltree::Node, css: &StyleSheet, st: &mut Style, vw: f64, vh: f64, charge_css: impl FnMut(usize) -> bool) -> (f64, bool) { + let d = declared(n, css, charge_css); + let num = |k: &str| { + d.get(k) + .and_then(|v| v.trim().trim_end_matches('%').parse::().ok().map(|x| if v.trim().ends_with('%') { x / 100.0 } else { x })) + .filter(|x| x.is_finite()) + }; + if let Some(c) = d.get("color").and_then(|v| parse_rgba_compat(v)) { + st.color = c; + } + let font_size = d.get("font-size").and_then(|v| match v.trim().strip_suffix('%') { + Some(p) => p.trim().parse::().ok().map(|p| p / 100.0 * st.font_size), + None => length(v, 'o', st.font_size, vw, vh), + }); + if let Some(v) = font_size.filter(|v| v.is_finite()) { + st.font_size = v; + } + if let Some(p) = d.get("fill").and_then(|v| paint_ref(v)) { + st.fill = p; + } + if let Some(p) = d.get("stroke").and_then(|v| paint_ref(v)) { + st.stroke = p; + } + if let Some(v) = num("fill-opacity") { + st.fill_opacity = v.clamp(0.0, 1.0); + } + if let Some(v) = num("stroke-opacity") { + st.stroke_opacity = v.clamp(0.0, 1.0); + } + if let Some(v) = d.get("stroke-width").and_then(|v| length(v, 'o', st.font_size, vw, vh)) { + st.stroke_width = v.max(0.0); + } + if let Some(v) = num("stroke-miterlimit") { + st.miter = v.max(1.0); + } + if let Some(v) = d.get("fill-rule") { + st.fill_rule = if v.trim() == "evenodd" { FillRule::EvenOdd } else { FillRule::NonZero }; + } + if let Some(v) = d.get("stroke-linecap") { + st.cap = match v.trim() { + "round" => Cap::Round, + "square" => Cap::Square, + _ => Cap::Butt, + }; + } + if let Some(v) = d.get("stroke-linejoin") { + st.join = match v.trim() { + "round" => Join::Round, + "bevel" => Join::Bevel, + _ => Join::Miter, + }; + } + if let Some(v) = d.get("stroke-dasharray") { + st.dash = if v.trim() == "none" { + None + } else { + let a: Vec = v + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|t| !t.is_empty()) + .filter_map(|t| length(t, 'o', st.font_size, vw, vh)) + .collect(); + if a.iter().all(|x| *x >= 0.0) && a.iter().any(|x| *x > 0.0) { Some(a) } else { None } + }; + } + if let Some(v) = d.get("stroke-dashoffset").and_then(|v| length(v, 'o', st.font_size, vw, vh)) { + st.dash_offset = v; + } + if let Some(v) = d.get("visibility") { + st.visible = !matches!(v.trim(), "hidden" | "collapse"); + } + let display = d.get("display").is_none_or(|v| v.trim() != "none"); + (num("opacity").unwrap_or(1.0).clamp(0.0, 1.0), display) +} + +/// Resolve a [`PaintRef`] against `st` and a caller-supplied `url(#id)` resolver. +pub fn resolve_paint(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(&str, Option<[f64; 4]>) -> UrlPaint) -> Option> { + match paint { + PaintRef::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + PaintRef::Current => Some(ResolvedPaint::Color([st.color[0], st.color[1], st.color[2]], st.color[3])), + PaintRef::Url(id, fallback) => match resolve_url(id, *fallback) { + UrlPaint::Server(s) => Some(ResolvedPaint::Server(s)), + UrlPaint::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + UrlPaint::Fallback => fallback.map(|c| ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + UrlPaint::None => None, + }, + } +} + +/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`. +pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> { + let (v, exceeded) = numbers_bounded(n.attribute("viewBox")?, 5); + if exceeded || !v.iter().all(|x| x.is_finite()) { + return None; + } + let [x, y, width, height] = v.as_slice() else { return None }; + (*width > 0.0 && *height > 0.0).then_some(([*x, *y], *width, *height)) +} + +/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`). +pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine { + let Some(([x, y], vw, vh)) = viewbox(n) else { return Affine::IDENTITY }; + let par = n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet"); + let mut parts = par.split_whitespace(); + let mut align = parts.next().unwrap_or("xMidYMid"); + if align == "defer" { + align = parts.next().unwrap_or("xMidYMid"); + } + let slice = parts.next() == Some("slice"); + let (sx, sy) = (w / vw, h / vh); + if align == "none" { + return Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)); + } + let s = if slice { sx.max(sy) } else { sx.min(sy) }; + let fx = if align.contains("xMid") { + 0.5 + } else if align.contains("xMax") { + 1.0 + } else { + 0.0 + }; + let fy = if align.contains("YMid") { + 0.5 + } else if align.contains("YMax") { + 1.0 + } else { + 0.0 + }; + let tx = (w - vw * s) * fx; + let ty = (h - vh * s) * fy; + Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::simple_css::parse as parse_css; + + #[test] + fn declared_precedence_and_transform_exclusion() { + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut css = StyleSheet::default(); + parse_css(".a { fill: green; stroke: red; }", &mut css).unwrap(); + css.index(); + let d = declared(rect, &css, |_| true); + assert_eq!(d.get("fill").map(String::as_str), Some("blue")); + assert_eq!(d.get("stroke").map(String::as_str), Some("red")); + assert!(!d.contains_key("transform")); + } + + #[test] + fn length_units_and_exponents() { + assert_eq!(length("10", 'x', 16.0, 200.0, 100.0), Some(10.0)); + assert_eq!(length("12pt", 'x', 16.0, 200.0, 100.0), Some(16.0)); + assert_eq!(length("1in", 'x', 16.0, 200.0, 100.0), Some(96.0)); + assert_eq!(length("2em", 'x', 16.0, 200.0, 100.0), Some(32.0)); + assert_eq!(length("2ex", 'x', 16.0, 200.0, 100.0), Some(16.0)); + assert_eq!(length("1e2em", 'x', 10.0, 200.0, 100.0), Some(1000.0)); + assert_eq!(length("50%", 'x', 16.0, 200.0, 100.0), Some(100.0)); + assert_eq!(length("50%", 'y', 16.0, 200.0, 100.0), Some(50.0)); + assert_eq!(length("nan", 'x', 16.0, 200.0, 100.0), None); + } + + #[test] + fn attr_len_reads_or_defaults_to_zero() { + let doc = roxmltree::Document::parse(r#""#).unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let st = Style::default(); + assert_eq!(attr_len(rect, "x", 'x', &st, 200.0, 100.0), 100.0); + assert_eq!(attr_len(rect, "y", 'y', &st, 200.0, 100.0), 0.0); + assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 0.0); + } + + #[test] + fn cascade_applies_inheritance_and_display() { + let doc = roxmltree::Document::parse( + r##""##, + ) + .unwrap(); + let g = doc.descendants().find(|n| n.tag_name().name() == "g").unwrap(); + let css = StyleSheet::default(); + let mut st = Style::default(); + let (opacity, display) = cascade(g, &css, &mut st, 100.0, 100.0, |_| true); + assert_eq!(opacity, 0.5); + assert!(!display); + assert!(!st.visible); + assert_eq!(st.font_size, 20.0); + assert_eq!(st.stroke_width, 40.0); + assert_eq!(st.fill, Some(PaintRef::Current)); + assert_eq!(st.fill_rule, FillRule::EvenOdd); + assert_eq!(st.cap, Cap::Round); + assert_eq!(st.join, Join::Bevel); + assert_eq!(st.dash, Some(vec![4.0, 2.0])); + } + + #[test] + fn paint_ref_and_resolve_paint_handle_fallbacks() { + assert_eq!(paint_ref("none"), Some(None)); + assert_eq!(paint_ref("inherit"), None); + assert_eq!(paint_ref("currentColor"), Some(Some(PaintRef::Current))); + assert_eq!(paint_ref("url(#grad) red"), Some(Some(PaintRef::Url("grad".into(), Some([1.0, 0.0, 0.0, 1.0]))))); + + let st = Style { color: [0.0, 1.0, 0.0, 0.5], ..Style::default() }; + assert_eq!(resolve_paint(&PaintRef::Current, &st, |_, _| UrlPaint::<()>::None), Some(ResolvedPaint::Color([0.0, 1.0, 0.0], 0.5))); + + let url = PaintRef::Url("g".into(), Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Server("ok")), Some(ResolvedPaint::Server("ok"))); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Fallback), Some(ResolvedPaint::Color([1.0, 0.0, 0.0], 1.0))); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::None), None); + } + + #[test] + fn viewbox_and_transform_preserve_aspect_ratio() { + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let root = doc.root_element(); + assert_eq!(viewbox(root), Some(([10.0, 20.0], 100.0, 50.0))); + let m = viewbox_transform(root, 200.0, 200.0); + // Scale is min(2, 4) = 2; tx = (200 - 200) * 1.0 = 0; ty = (200 - 100) * 0.5 = 50. + let p = m * kurbo::Point::new(10.0, 20.0); + assert_eq!(p, kurbo::Point::new(0.0, 50.0)); + } +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 15fa33b1e..4a245de91 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -38,3 +38,6 @@ pub mod simple_css; /// Prefix-preserving SVG transform-list compatibility. pub mod transform_compat; + +/// Compatibility SVG document/CSS interpretation helpers (style cascade, lengths, paints, viewBox). +pub mod doc_style; diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs index 8db13faa2..16d2f3de5 100644 --- a/crates/svg/src/path_data.rs +++ b/crates/svg/src/path_data.rs @@ -125,6 +125,26 @@ pub enum Segment { Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point }, } +/// One `M …` run of a `d` attribute, preserving quadratic (`Q`/`T`) segments. +#[derive(Debug, Clone, PartialEq)] +pub struct QuadSubpath { + /// Start point. + pub start: Point, + /// Segments in drawing order. + pub segs: Vec, + /// Whether a close-path command closed this subpath. + pub closed: bool, +} + +/// A path segment that preserves quadratic Bézier curves alongside lines, cubics, and arcs. +#[derive(Debug, Clone, PartialEq)] +pub enum QuadSegment { + Line(Point), + Quad(Point, Point), + Cubic(Point, Point, Point), + Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point }, +} + /// Tokens of a `d` attribute: command letters and numbers, in order. enum Tok { Cmd(u8), @@ -174,15 +194,51 @@ impl<'a> Tokenizer<'a> { } } -/// Split `d` into subpaths, resolving relative commands and the S/T control reflections. +/// Split `d` into subpaths, resolving relative commands and S/T control reflections while +/// raising quadratic (`Q`/`T`) segments to cubics. pub fn parse_path(d: &str) -> Result> { + Ok(parse_path_with_quads(d)? + .into_iter() + .map(|sub| { + let mut cur = sub.start; + let segs = sub + .segs + .into_iter() + .map(|seg| match seg { + QuadSegment::Line(p) => { + cur = p; + Segment::Line(p) + } + QuadSegment::Quad(q, p) => { + let out = Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p); + cur = p; + out + } + QuadSegment::Cubic(c1, c2, p) => { + cur = p; + Segment::Cubic(c1, c2, p) + } + QuadSegment::Arc { rx, ry, rot, large, sweep, end } => { + cur = end; + Segment::Arc { rx, ry, rot, large, sweep, end } + } + }) + .collect(); + Subpath { start: sub.start, segs, closed: sub.closed } + }) + .collect()) +} + +/// Split `d` into subpaths, resolving relative commands and S/T control reflections while +/// preserving quadratic (`Q`/`T`) segments. +pub fn parse_path_with_quads(d: &str) -> Result> { let mut tk = Tokenizer::new(d); let mut lookahead: Option = None; let mut cmd = 0u8; let mut cur = Point::ZERO; let mut start = Point::ZERO; - let mut segs: Vec = Vec::new(); - let mut out: Vec = Vec::new(); + let mut segs: Vec = Vec::new(); + let mut out: Vec = Vec::new(); let closed = false; let mut prev_cubic: Option = None; let mut prev_quad: Option = None; @@ -214,7 +270,7 @@ pub fn parse_path(d: &str) -> Result> { Tok::Cmd(c) => { if c.eq_ignore_ascii_case(&b'z') { if !segs.is_empty() { - out.push(Subpath { start, segs, closed: true }); + out.push(QuadSubpath { start, segs, closed: true }); segs = Vec::new(); } cur = start; @@ -264,7 +320,7 @@ pub fn parse_path(d: &str) -> Result> { match abs { b'M' => { if !segs.is_empty() { - out.push(Subpath { start, segs, closed: false }); + out.push(QuadSubpath { start, segs, closed: false }); segs = Vec::new(); } cur = point(args[0], args[1]); @@ -275,25 +331,25 @@ pub fn parse_path(d: &str) -> Result> { } b'L' => { cur = point(args[0], args[1]); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'H' => { cur = Point::new(if rel { cur.x + args[0] } else { args[0] }, cur.y); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'V' => { cur = Point::new(cur.x, if rel { cur.y + args[0] } else { args[0] }); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'C' => { let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5])); - segs.push(Segment::Cubic(c1, c2, p)); + segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); prev_quad = None; cur = p; @@ -301,14 +357,14 @@ pub fn parse_path(d: &str) -> Result> { b'S' => { let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2); let (c2, p) = (point(args[0], args[1]), point(args[2], args[3])); - segs.push(Segment::Cubic(c1, c2, p)); + segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); prev_quad = None; cur = p; } b'Q' => { let (q, p) = (point(args[0], args[1]), point(args[2], args[3])); - segs.push(Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p)); + segs.push(QuadSegment::Quad(q, p)); prev_quad = Some(q); prev_cubic = None; cur = p; @@ -316,14 +372,14 @@ pub fn parse_path(d: &str) -> Result> { b'T' => { let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q); let p = point(args[0], args[1]); - segs.push(Segment::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p)); + segs.push(QuadSegment::Quad(reflect, p)); prev_quad = Some(reflect); prev_cubic = None; cur = p; } b'A' => { let end = point(args[5], args[6]); - segs.push(Segment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end }); + segs.push(QuadSegment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end }); cur = end; prev_cubic = None; prev_quad = None; @@ -339,7 +395,7 @@ pub fn parse_path(d: &str) -> Result> { } } if !segs.is_empty() { - out.push(Subpath { start, segs, closed }); + out.push(QuadSubpath { start, segs, closed }); } Ok(out) } @@ -443,6 +499,17 @@ mod tests { assert_eq!(paths[0].segs[1], Segment::Cubic(Point::new(8.0, -2.0), Point::new(10.0, -2.0), Point::new(12.0, 0.0))); } + #[test] + fn parse_path_with_quads_preserves_quadratic_control_points() { + let paths = parse_path_with_quads("M0 10 Q5 20 10 10 T20 10 Z").unwrap(); + assert_eq!(paths.len(), 1); + assert!(paths[0].closed); + assert_eq!( + paths[0].segs, + vec![QuadSegment::Quad(Point::new(5.0, 20.0), Point::new(10.0, 10.0)), QuadSegment::Quad(Point::new(15.0, 0.0), Point::new(20.0, 10.0)),] + ); + } + #[test] fn close_resets_smooth_control_history() { // After Z, S must not reflect the preceding C's control (20,20) → (0,0). diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index af3eec992..7fb498691 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -229,12 +229,22 @@ pub fn path_data(path: &BezPath) -> String { /// Path data with `decimals` decimals per coordinate, written compactly: `M1.00 2.00L3.50 2.00Z`. /// Coordinates that are not finite are written as zero. pub fn path_data_fixed(path: &BezPath, decimals: usize) -> String { + path_data_with_format(path, |value| num(value, decimals)) +} + +/// Compact absolute path commands with caller-owned coordinate formatting. +/// +/// The formatter is called once per coordinate, in path order. It must produce a valid SVG +/// number (including handling nonfinite inputs); it controls rounding and negative zero. +/// Command letters and separators are shared, while the application's precision policy stays +/// with the caller. No intermediate geometry or coordinate collection is allocated. +pub fn path_data_with_format(path: &BezPath, mut format: impl FnMut(f64) -> T) -> String { let mut d = String::new(); let mut command = |letter: char, points: &[Point]| { d.push(letter); for (i, p) in points.iter().enumerate() { let sep = if i == 0 { "" } else { " " }; - let _ = write!(d, "{sep}{} {}", num(p.x, decimals), num(p.y, decimals)); + let _ = write!(d, "{sep}{} {}", format(p.x), format(p.y)); } }; for el in path.elements() { @@ -400,6 +410,25 @@ mod tests { p } + #[test] + fn custom_path_format_keeps_commands_and_coordinate_order() { + let mut path = BezPath::new(); + path.move_to((1.0, 2.0)); + path.line_to((3.0, 4.0)); + path.quad_to((5.0, 6.0), (7.0, 8.0)); + path.curve_to((9.0, 10.0), (11.0, 12.0), (13.0, 14.0)); + path.close_path(); + let mut seen = Vec::new(); + let output = path_data_with_format(&path, |v| { + seen.push(v); + v + }); + assert_eq!(output, "M1 2L3 4Q5 6 7 8C9 10 11 12 13 14Z"); + assert_eq!(seen, (1..=14).map(f64::from).collect::>()); + assert_eq!(BezPath::from_svg(&output).unwrap(), path); + assert_eq!(path_data_with_format(&BezPath::new(), |_: f64| -> String { panic!("empty path") }), ""); + } + #[test] fn scene_can_keep_fixed_view_box_without_changing_default_output() { let scene = Scene { width_mm: 100.0, height_mm: 150.0, view_box: [0.0, 0.0, 100.0, 150.0], elements: vec![] }; diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index c4844b832..b5f9dd435 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -1082,7 +1082,7 @@ fn a_held_space_pans_over_a_canvas_control_and_leaves_it_unchanged() { fn a_queued_space_whose_hand_the_gate_refuses_leaves_the_press_to_the_selected_tool() { let log = Log::default(); let (mut fixture, view, canvas) = momentary_canvas(Probe::new("main", &log)); - fixture.gate(CommandGate::new(|command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); + fixture.gate(CommandGate::new((), |_: &(), command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); let at = fixture.by_role(Role::CANVAS)[0].rect.center(); let before = view.get().expect("the canvas ran").center; let space = craft_keymap::Key::Space; diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index d6ee47c52..701f2643e 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -52,7 +52,7 @@ impl MeasureCx<'_, C> { /// `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above /// the component, and the enabled state of its instance. `None` when the command is scoped and no instance of /// its scope is above the component. - pub fn resolve_command(&self, command: impl Into) -> Option { + pub fn resolve_command(&self, command: impl Into) -> Option> { commands::resolve_scoped(self.ui.ctx(), self.env.command_chain(), &command.into()) } diff --git a/crates/ui-contract/src/contract/steps/env.rs b/crates/ui-contract/src/contract/steps/env.rs index 1fa643e51..cbb9d58de 100644 --- a/crates/ui-contract/src/contract/steps/env.rs +++ b/crates/ui-contract/src/contract/steps/env.rs @@ -33,7 +33,7 @@ pub(crate) fn variants(asked: Option) -> (Variant, Varian /// size; variant; label. /// `(requested, variant)` comes from `variants`. pub(crate) fn env(ctx: &Context, env: &Env, common: &Common, (requested, variant): (Variant, Variant)) -> EnvStep { - let command = common.command.as_ref().map(|command| Arc::new(commands::resolve_bound(ctx, &env.commands, command))); + let command = common.command.as_ref().map(|command| commands::resolve_bound(ctx, &env.commands, command)); let label = match (&common.label, &command) { (Label::Empty, Some(command)) => Label::Shared(command.label.clone()), (label, _) => label.resolved(&env.words), diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 85673f2e0..d1a00b31c 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -5,9 +5,12 @@ use super::{ AppCatalog, CommandChain, CommandGate, CommandInput, CommandScope, CommandSet, CommandState, EditCommands, FirePhase, FireSource, Fired, ResolvedCommand, WindowShortcut, registry, }; +use crate::contract::Revision; use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::egui::{pass, repaint}; use crate::runtime::focus::EditSet; +#[cfg(feature = "testing")] +use crate::runtime::measure::Resolve; use crate::runtime::pass_state; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler}; @@ -48,13 +51,24 @@ impl Instances { self.list.iter() } - /// Registers `instance`, keeping the place of one already registered under the same id. - fn upsert(&mut self, instance: Instance) { + /// Registers `instance`, keeping the place of one already registered under the same id. Returns whether a + /// resolution can see the difference: the id is new or was dead, or its scope, viewport or layer changed. + fn upsert(&mut self, instance: Instance) -> bool { match self.at.get(&instance.id) { - Some(at) => self.list[*at] = instance, + Some(at) => { + let held = &self.list[*at]; + // A held instance that missed a pass is dead until it registers again: its return is seen too. + let seen = held.stamp + 1 < instance.stamp + || held.scope != instance.scope + || held.viewport != instance.viewport + || held.layer != instance.layer; + self.list[*at] = instance; + seen + } None => { self.at.insert(instance.id, self.list.len()); self.list.push(instance); + true } } } @@ -110,13 +124,25 @@ pub(crate) struct Board { app: Option, keymap: Option, gate: Option, - /// The gate's answers in this frame, by command key (`CommandRef::key`). The gate answers from what the app knew - /// before the frame, so the board asks it once per command per frame, whichever readers and passes resolve it. + /// The gate's answers under its current key, by command key (`CommandRef::key`). The gate is a `fn` of its props, + /// so the board asks it once per command until the key moves, whichever readers, passes and frames resolve it. gate_answers: HashMap, /// Command ids by number, so a state lookup allocates nothing. numbers: HashMap, + /// The app-scope states of the app's `Tracked`, by command number, and the revision they are of. + app_states: HashMap, + app_revision: Option, + /// The states instances published this frame and last frame; a resolution reads this frame's, else last frame's. this: HashMap, last: HashMap, + /// The revision of each state key that has changed: the value of `state_seq` when it last did. + revisions: HashMap, + /// Moves with every state change. + state_seq: u64, + /// The state keys that changed, with the `state_seq` of each change, since the oldest wake of a kept table. + state_log: Vec<(u64, StateKey)>, + /// The generations of the inputs every resolution reads and of the focus vantage. + gens: Gens, /// What the frame's input changed, under the root frame it arrived for (`set_input`). changed: (u64, InputChanges), /// Scoped commands waiting for their instance. @@ -133,8 +159,8 @@ pub(crate) struct Board { before: HashMap, /// Where the commands of the running pass are judged from: the key focus and the modal layers. here: Vantage, - /// The chain of the last pass in which any component held key focus. - last_focused: Vec, + /// Each viewport's own vantage facts. + views: HashMap, matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. @@ -149,8 +175,8 @@ pub(crate) struct Board { unknown: HashSet, /// App catalog ids that a linked set also defines, already logged. shadowed: HashSet, - /// What each reader was shown, by the state key it read and its viewport (`note_read`). - shown: ShownMap, + /// What each reader was shown, by viewport (`read`). + shown: HashMap, /// The scope each child scope is declared inside: an instance of the child is also an instance of the parent. parents: HashMap<&'static str, &'static str>, } @@ -168,7 +194,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { a.cloned().unwrap_or_default() == b.cloned().unwrap_or_default() } -/// Who read a command's resolution: the vantage `begin` resolves it from again. +/// Who read a command's resolution: the vantage it is resolved from again. #[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. @@ -182,36 +208,275 @@ enum Reader { InMenu(Id, CommandChain), } -/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The -/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order. -type ShownMap = HashMap>>; +impl Reader { + /// The reader's kind, for the testing check's message. + #[cfg(feature = "testing")] + fn kind(&self) -> &'static str { + match self { + Reader::Global => "global", + Reader::Beneath(_) => "beneath-layer", + Reader::Chain(_) => "component", + Reader::InMenu(..) => "in-menu", + } + } -/// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before. -fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) { - keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved); -} - -fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) { - match readers.iter_mut().find(|(kept, _)| *kept == reader) { - Some((_, kept)) => kept.clone_from(resolved), - None => readers.push((reader, resolved.clone())), + /// The layer or menu whose vantage this reader is judged from, which the reader goes with when it closes. + fn layer(&self) -> Option { + match self { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => Some(*layer), + _ => None, + } } } -/// Notes, in the read record, that the running code showed the state under `key`, and keeps what `reader` was shown: a -/// settled region that showed it runs when `begin` resolves the command from the same reader to something else (a -/// state, the gate, a modal layer or an instance changed), and a change published after it in the pass runs the pass -/// again. -fn note_read(ctx: &Context, key: Option, reader: Reader, resolved: &ResolvedCommand) { - let Some((number, instance)) = key else { return }; - reads::note(ctx, BindKey::Command(number, instance), Id::NULL, measure::active(ctx), &[]); - let viewport = pass::current_viewport(ctx); - with(ctx, |board| keep_shown(&mut board.shown, (number, instance), viewport, reader, resolved)); +/// The generations of what resolutions read beside states and the gate, across the viewports. +#[derive(Clone, Copy, Default, PartialEq)] +struct Gens { + /// Read by every resolution: the keymap, the app catalog and the registry, the scope parents, the instances and + /// their liveness, and the modal facts (open layers, their roots, the states published inside them, the held-open + /// canvas). + shared: u64, + /// Read by a resolution that picks an instance: the instances around the focus in every viewport. + focus: u64, +} + +/// The generations of one viewport's own vantage facts. +#[derive(Clone, Copy, Default, PartialEq)] +struct ViewGens { + /// Read by every resolution in the viewport: a dialog owns the keys at its focus. + keys: u64, + /// Read by a resolution that picks an instance or reaches by focus: the chain last focused in the viewport and the + /// instances of its focus chain inside the top modal layer. + focus: u64, + /// Read by a resolution the focused stop answered: the edits that stop takes and those of them that do nothing now. + edits: u64, +} + +/// One viewport's vantage facts as its last `begin` set them, and their generations. A viewport's `begin` compares +/// with its own, so two windows never move each other's. +#[derive(Default)] +struct View { + /// The chain of the last pass in which any component of the viewport held key focus. + last_focused: Vec, + inside_modal: Vec, + dialog_keys: bool, + /// The focused stop's edits and those of them that do nothing now. The focus record changes only in an end hook, + /// so the value `begin` reads holds for the pass. + edits: Option<(EditSet, EditSet)>, + gens: ViewGens, +} + +/// What a resolution read besides the board's own generation and the gate. +#[derive(Default)] +struct Reads { + /// It picked an instance for a source with no component of its own, or reached by the focus. + focus: bool, + /// The focused stop answered for the command, or was asked: it read that stop's edits. + edits: bool, +} + +/// The inputs a kept resolution was made from: it holds while each is unchanged. +#[derive(Clone, PartialEq)] +struct ResolveKey { + shared: u64, + /// The viewport's keys generation. + keys: u64, + /// The focus generations, across the viewports and the viewport's own, when the resolution read the focus. + focus: Option<(u64, u64)>, + /// The state key read and its revision. + state: Option<(StateKey, u64)>, + /// The gate's key and its answer, with a gate. + gate: Option<(u128, bool)>, + /// The viewport's edits generation, when the resolution read the focused stop's edits. + edits: Option, + /// The vantage of a reader under a layer or inside a menu (`None` inside: no stop to return to). + vantage: Option>, + /// The command's number, which a resolution the focused stop answered is noted under. + number: u32, +} + +impl ResolveKey { + /// The key a region that showed the resolution read it under: the state's, else the focused stop's answer. + fn bind(&self) -> Option { + match (self.state, self.edits) { + (Some(((number, instance), _)), _) => Some(BindKey::Command(number, instance)), + (None, Some(_)) => Some(BindKey::FocusedEdit(self.number)), + (None, None) => None, + } + } +} + +/// A resolution a reader was shown, and what it was made from. +struct Kept { + resolved: Arc, + key: ResolveKey, +} + +/// The inputs as a viewport's last wake saw them. +#[derive(Clone, Copy, Default, PartialEq)] +struct Woke { + gens: Gens, + view: ViewGens, + state_seq: u64, + gate: Option, +} + +/// A kept resolution and who it was kept for. +struct Entry { + reader: Reader, + kept: Kept, +} + +/// What each reader of a viewport was shown, with indexes from each input to the entries that read it, so a wake walks +/// only the entries whose inputs moved. +#[derive(Default)] +struct Shown { + entries: HashMap, + next: u64, + /// By reader and command number (a command's parameter variants share the number). + by_reader: HashMap>>, + /// By the state key read. + by_state: HashMap>, + /// The entries that read the focus generations. + by_focus: HashSet, + /// The entries that read the focused stop's edits. + by_edits: HashSet, + /// The entries of readers under a layer or inside a menu, whose vantage every wake reads again. + layered: HashSet, + /// The inputs at the last wake. + woke: Option, +} + +impl Shown { + fn index(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + let key = &entry.kept.key; + if let Some((state, _)) = key.state { + self.by_state.entry(state).or_default().insert(id); + } + if key.focus.is_some() { + self.by_focus.insert(id); + } + if key.edits.is_some() { + self.by_edits.insert(id); + } + if entry.reader.layer().is_some() { + self.layered.insert(id); + } + } + + fn unindex(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + if let Some((state, _)) = entry.kept.key.state + && let Some(ids) = self.by_state.get_mut(&state) + { + ids.remove(&id); + if ids.is_empty() { + self.by_state.remove(&state); + } + } + self.by_focus.remove(&id); + self.by_edits.remove(&id); + self.layered.remove(&id); + } + + /// The entry `reader` keeps for `command`. + fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { + let ids = self.by_reader.get(reader)?.get(&number)?; + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + } + + /// Keeps `kept` for `reader`, in place of what it kept for the same command. + fn keep(&mut self, reader: Reader, number: u32, kept: Kept) { + match self.find(&reader, number, &kept.resolved.command) { + Some(id) => self.replace(id, kept), + None => { + let id = self.next; + self.next += 1; + self.by_reader.entry(reader.clone()).or_default().entry(number).or_default().push(id); + self.entries.insert(id, Entry { reader, kept }); + self.index(id); + } + } + } + + /// `kept` in place of entry `id`'s, indexed under its inputs. + fn replace(&mut self, id: u64, kept: Kept) { + self.unindex(id); + if let Some(entry) = self.entries.get_mut(&id) { + entry.kept = kept; + } + self.index(id); + } + + /// Drops the entries `drop` names. + fn drop_where(&mut self, mut drop: impl FnMut(&Entry) -> bool) { + let gone: Vec = self.entries.iter().filter(|(_, entry)| drop(entry)).map(|(id, _)| *id).collect(); + for id in gone { + self.unindex(id); + if let Some(entry) = self.entries.remove(&id) { + let number = entry.kept.key.number; + if let Some(by_number) = self.by_reader.get_mut(&entry.reader) { + if let Some(ids) = by_number.get_mut(&number) { + ids.retain(|at| *at != id); + if ids.is_empty() { + by_number.remove(&number); + } + } + if by_number.is_empty() { + self.by_reader.remove(&entry.reader); + } + } + } + } + } +} + +/// Whether `key` still holds under the board's `gens`, the viewport's `view` generations, `revisions`, the current +/// `gate` answer and the reader's `vantage`. A gate whose key moved but whose answer is the same keeps the resolution, +/// under the new key. +fn holds( + key: &mut ResolveKey, + gens: Gens, + view: ViewGens, + revisions: &HashMap, + gate: Option<(u128, bool)>, + vantage: Option<&Option>, +) -> bool { + let same = key.shared == gens.shared + && key.keys == view.keys + && key.focus.is_none_or(|focus| focus == (gens.focus, view.focus)) + && key.edits.is_none_or(|edits| edits == view.edits) + && key.state.is_none_or(|(state, revision)| revisions.get(&state).copied().unwrap_or(0) == revision) + && key.vantage.as_ref() == vantage; + let gate = match (key.gate, gate) { + (kept, now) if kept == now => true, + (Some((_, kept)), Some((now, answer))) if kept == answer => { + key.gate = Some((now, answer)); + true + } + _ => false, + }; + same && gate +} + +/// The edits of the stop that holds key focus in `viewport`, and those of them that do nothing now. +fn focused_edits(ctx: &Context, viewport: ViewportId) -> Option<(EditSet, EditSet)> { + focus::record(ctx, viewport).keys.map(|keys| (keys.edits, keys.inactive)) +} + +/// Notes, in the read record, that the running code showed a resolution under `key` (a state's, or the focused stop's +/// answer): a settled region that showed it runs when `begin` resolves the command from the same reader to something +/// else (a state, the gate, a modal layer, an instance or the stop's edits changed), and a change published after it in +/// the pass runs the pass again. +fn note_read(ctx: &Context, key: Option) { + let Some(key) = key else { return }; + reads::note(ctx, key, Id::NULL, measure::active(ctx), &[]); } /// Where a resolution judges a command from: the modal facts and the focus. The board's own is the key focus of the /// running pass; a surface that closes before its command runs (the palette) judges from the window under it. -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq)] struct Vantage { /// A modal layer blocks a window. modal_open: bool, @@ -234,7 +499,64 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Board) -> R) -> R { pass_state::with::(ctx, f) } +/// What a reader's lookup found. +enum Lookup { + /// A kept resolution whose inputs are unchanged, and the key it was read under. + Fresh(Arc, Option), + /// A kept resolution some input of which changed. + Stale, + /// None. + Missing, +} + impl Board { + /// Notes that the state under `key` changed: the readers of it resolve again. + fn bump_state(&mut self, key: StateKey) { + self.state_seq += 1; + self.revisions.insert(key, self.state_seq); + self.state_log.push((self.state_seq, key)); + } + + /// The gate's key and its answer for `command`, asking it once per command under each key. + fn gate_answer(&mut self, command: &CommandRef) -> Option<(u128, bool)> { + let gate = self.gate.as_ref()?; + let answer = match self.gate_answers.get(command.key_text().as_ref()) { + Some(answer) => *answer, + None => { + let answer = gate.allows(command); + self.gate_answers.insert(command.key(), answer); + answer + } + }; + Some((gate.key(), answer)) + } + + /// The generations of `viewport`'s own vantage facts. + fn view_gens(&self, viewport: ViewportId) -> ViewGens { + self.views.get(&viewport).map_or_else(ViewGens::default, |view| view.gens) + } + + /// What `reader` of `viewport` was shown of `command`, judged from `vantage` (a layered reader's). + fn lookup(&mut self, viewport: ViewportId, reader: &Reader, command: &CommandRef, vantage: Option<&Option>) -> Lookup { + let Some(&number) = self.numbers.get(command.id.as_str()) else { return Lookup::Missing }; + let gate = self.gate_answer(command); + let view = self.view_gens(viewport); + let Some(shown) = self.shown.get_mut(&viewport) else { return Lookup::Missing }; + let Some(id) = shown.find(reader, number, command) else { return Lookup::Missing }; + let Some(entry) = shown.entries.get_mut(&id) else { return Lookup::Missing }; + if holds(&mut entry.kept.key, self.gens, view, &self.revisions, gate, vantage) { + Lookup::Fresh(Arc::clone(&entry.kept.resolved), entry.kept.key.bind()) + } else { + Lookup::Stale + } + } + + /// Keeps `resolved`, made from `key`, as what `reader` of `viewport` was shown. + fn keep(&mut self, viewport: ViewportId, reader: Reader, resolved: Arc, key: ResolveKey) { + let number = key.number; + self.shown.entry(viewport).or_default().keep(reader, number, Kept { resolved, key }); + } + fn live(&self, ctx: &Context, instance: &Instance) -> bool { instance.stamp + 1 >= pass::pass_nr(ctx, instance.viewport) } @@ -332,7 +654,8 @@ impl Board { fn pick(&self, ctx: &Context, scope: &str, from: &Vantage) -> Option { // The held-open canvas ranks below every instance around the focus. let focused: Vec = self.held_open.into_iter().chain(from.focused.iter().flat_map(|(_, chain)| chain.iter().copied())).collect(); - pick_instance(&self.live_instances(ctx, scope), &focused, &self.last_focused) + let last = self.views.get(&pass::current_viewport(ctx)).map_or(&[][..], |view| view.last_focused.as_slice()); + pick_instance(&self.live_instances(ctx, scope), &focused, last) } /// The non-app scopes around the focus, innermost first. An instance of a child scope also brings the scopes it @@ -370,7 +693,8 @@ impl Board { /// Who answers for `command` ahead of the app: an instance inside the top modal layer that published its state, /// else the focused component when it takes the command as an edit (inside a modal layer, only when the focus /// is in it). - fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage) -> Option { + fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> Option { + reads.focus = true; let dialog_open = from.modal_open || from.dialog_keys; let number = *self.numbers.get(command.id.as_str())?; let published = self.modal_published.iter().chain(&self.modal_published_last).find(|(published, _)| *published == number); @@ -378,10 +702,13 @@ impl Board { return Some(Declaration::Instance(id)); } let edit = self.registry.edit_of(&command.id)?; - let keys = from - .edits - .map(|edits| (edits, from.inactive.unwrap_or(EditSet::NONE))) - .or_else(|| focus::record(ctx, pass::current_viewport(ctx)).keys.map(|keys| (keys.edits, keys.inactive))); + let keys = match from.edits { + Some(edits) => Some((edits, from.inactive.unwrap_or(EditSet::NONE))), + None => { + reads.edits = true; + focused_edits(ctx, pass::current_viewport(ctx)) + } + }; let in_reach = !dialog_open || !from.inside_modal.is_empty(); let (edits, inactive) = keys.filter(|_| in_reach)?; edits.contains(edit).then_some(Declaration::Focused { inactive: inactive.contains(edit) }) @@ -396,6 +723,7 @@ impl Board { instance: Option, reach: Reach<'_>, from: &Vantage, + reads: &mut Reads, ) -> (ResolvedCommand, Option) { let def = self.def(&command.id); let app = self.to_app(self.scope_of(command)); @@ -404,7 +732,7 @@ impl Board { // A command no set registers is never blocked. let rule = def.map(|def| def.modal); // The instance inside the top modal that declares the command, which then answers for it. - let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from)).flatten(); + let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from, reads)).flatten(); // The declaring instance answers for the command: it is where the command is delivered. The focused component // answers for itself, so the app's state of the command does not apply. let instance = match declaring { @@ -416,13 +744,20 @@ impl Board { Some(Declaration::Focused { .. }) => None, None => self.state_key(command, instance), }; - let this = key.and_then(|key| self.this.get(&key)); - let last = key.and_then(|key| self.last.get(&key)); + // An app-scope state is the app's held one; an instance's is this frame's publish, else last frame's. + let (this, last) = match key { + Some((number, None)) => (self.app_states.get(&number), None), + Some(key) => (self.this.get(&key), self.last.get(&key)), + None => (None, None), + }; let state = this.or(last); let flags = resolve_flags(this.map(CommandState::flags), last.map(CommandState::flags)); let reached = declaring.is_some() || instance.is_some_and(|id| match reach { - Reach::Focus => from.inside_modal.contains(&id), + Reach::Focus => { + reads.focus = true; + from.inside_modal.contains(&id) + } Reach::Chain(chain) => chain.ids().skip_while(|at| !self.is_modal_root(*at)).any(|at| at == id), }); let modal = !dialog_open @@ -494,7 +829,10 @@ fn chord_input(chord: &Chord) -> KeyInput { /// Loads the linked command sets; the stories' sets only with `stories`. pub(crate) fn install(ctx: &Context, stories: bool) -> Result<(), registry::CommandDefError> { let registry = registry::Registry::shared(stories)?; - with(ctx, |board| board.registry = registry); + with(ctx, |board| { + board.registry = registry; + board.gens.shared += 1; + }); Ok(()) } @@ -651,7 +989,9 @@ fn keymap_for(registry: &Arc, app: Option<&AppCatalog>, plat #[doc(hidden)] pub fn declare_child(ctx: &Context, child: CommandScope, parent: CommandScope) { with(ctx, |board| { - board.parents.insert(child.name(), parent.name()); + if board.parents.insert(child.name(), parent.name()) != Some(parent.name()) { + board.gens.shared += 1; + } }); } @@ -665,24 +1005,48 @@ fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } -/// Before each frame: last frame's state is the fallback, the app's states, gate and catalog are this frame's, and the -/// keymap follows the user's overrides and the catalog's generation. The readers of a state that changed run from -/// `begin`, which resolves again what each was shown. +/// Before each frame: the states instances published last frame are the fallback, the app's states are read again +/// when their revision moved, the gate and the catalog are this frame's, and the keymap follows the user's overrides +/// and the catalog's generation. The readers of an input that changed run from `begin`, which resolves again what each +/// was shown. pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { let platform = platform(ctx); let frame = pass::root_frame_nr(ctx); let generation = input.catalog.as_ref().map(AppCatalog::generation); let shadowed = with(ctx, |board| { - let mut states = HashMap::new(); - for (command, state) in &input.states { - let number = board.number(&command.id); - states.insert((number, None), state.clone()); + // A published state resolves from this frame's, else the last frame's: one published last frame and not again + // is gone now. + let gone: Vec = board.last.keys().filter(|key| !board.this.contains_key(key)).copied().collect(); + board.last = std::mem::take(&mut board.this); + for key in gone { + board.bump_state(key); + } + if board.modal_published_last.iter().any(|key| !board.modal_published.contains(key)) { + board.gens.shared += 1; } - // A state resolves from this frame's, else the last frame's. - board.last = std::mem::replace(&mut board.this, states); board.modal_published_last = std::mem::take(&mut board.modal_published); + let revision = input.states.as_ref().map(|(revision, _)| *revision); + if revision != board.app_revision { + board.app_revision = revision; + let mut states = HashMap::new(); + for (command, state) in input.states.iter().flat_map(|(_, states)| states.iter()) { + states.insert(board.number(&command.id), state.clone()); + } + let changed: Vec = states + .iter() + .filter(|(number, state)| board.app_states.get(number) != Some(*state)) + .map(|(number, _)| *number) + .chain(board.app_states.keys().filter(|number| !states.contains_key(number)).copied()) + .collect(); + board.app_states = states; + for number in changed { + board.bump_state((number, None)); + } + } + if input.gate.as_ref().map(CommandGate::key) != board.gate.as_ref().map(CommandGate::key) { + board.gate_answers.clear(); + } board.gate = input.gate.clone(); - board.gate_answers.clear(); board.app = input.catalog.clone(); let stale = board.keymap.as_ref().is_none_or(|cache| { cache.platform != platform @@ -699,6 +1063,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); + board.gens.shared += 1; for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -765,7 +1130,11 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); + with(ctx, |board| { + if board.instances.upsert(Instance { id, scope, viewport, stamp, layer }) { + board.gens.shared += 1; + } + }); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -788,11 +1157,14 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option) { with(ctx, |board| { - board.here.modal_open = open; - match root { + let held = match root { Some(root) => board.modal_roots.insert(viewport, root), None => board.modal_roots.remove(&viewport), }; + if board.here.modal_open != open || held != root { + board.gens.shared += 1; + } + board.here.modal_open = open; }); } @@ -849,51 +1221,51 @@ fn vantage_under(ctx: &Context, layer: Id, stop: Option<(focus::StopRec, Vec } /// `command` as seen by `instance` (`None` for the app) from `from` (`None`: the key focus of the running pass), with -/// the gate applied outside the board's lock, and the key of the state it read. +/// the gate applied, and the inputs it was made from; `reads` holds what the caller read to find the instance. fn resolve_in( ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>, -) -> (ResolvedCommand, Option) { - let ((mut resolved, key), first_unknown, gate) = with(ctx, |board| { + mut reads: Reads, +) -> (ResolvedCommand, ResolveKey) { + let (resolved, key, first_unknown) = with(ctx, |board| { let first_unknown = board.def(&command.id).is_none() && board.unknown.insert(command.id.clone()); // A command no state named yet has a key too, so a state given later reaches the regions that read it. board.number(&command.id); - let resolved = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here)); - // This frame's answer, else the gate to ask. - let gate = board.gate.as_ref().map(|gate| board.gate_answers.get(command.key_text().as_ref()).copied().ok_or_else(|| gate.clone())); - (resolved, first_unknown, gate) + let (mut resolved, state) = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here), &mut reads); + let gate = board.gate_answer(command); + if gate.is_some_and(|(_, allowed)| !allowed) { + resolved.enabled = false; + } + let view = board.view_gens(pass::current_viewport(ctx)); + let key = ResolveKey { + shared: board.gens.shared, + keys: view.keys, + focus: reads.focus.then_some((board.gens.focus, view.focus)), + state: state.map(|state| (state, board.revisions.get(&state).copied().unwrap_or(0))), + gate, + edits: reads.edits.then_some(view.edits), + vantage: None, + number: board.numbers.get(command.id.as_str()).copied().unwrap_or(u32::MAX), + }; + (resolved, key, first_unknown) }); if first_unknown { log::warn!("the command {} is in no registered command set: it is an app command with its id as its label", command.id); } - let allowed = match gate { - None => true, - Some(Ok(answer)) => answer, - Some(Err(gate)) => { - let answer = gate.allows(command); - with(ctx, |board| { - board.gate_answers.insert(command.key(), answer); - }); - answer - } - }; - if !allowed { - resolved.enabled = false; - } (resolved, key) } /// `command` for a surface with no component of its own: against the instance that `fire` would target. -pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> Arc { read(ctx, Reader::Global, command) } /// `command` for a surface with no component of its own that closes before its command runs, from the window under /// the modal layer `layer` (`beneath`). -pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> Arc { read(ctx, Reader::Beneath(layer), command) } @@ -903,7 +1275,7 @@ pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> /// group whose button opened it, focused or not), judged from the stop focus returns to once the menus close, which /// gives the edits, the modal facts and the instance when the chain holds none (Cut in a text field's edit menu follows /// the field's selection; an Edit menu row reaches the field that held focus); its activation fires that resolution. -pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Arc { let reader = match focus::running_menu(ctx) { Some(menu) => Reader::InMenu(menu, chain.clone()), None => Reader::Chain(chain.clone()), @@ -911,89 +1283,198 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma read(ctx, reader, command) } -/// `command` as `reader` is shown it, noted as its read. -fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> ResolvedCommand { - let (resolved, key) = resolve_as(ctx, &reader, command); - note_read(ctx, key, reader, &resolved); +/// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new +/// one, kept. +fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc { + let viewport = pass::current_viewport(ctx); + let vantage = vantage_of(ctx, &reader); + let found = with(ctx, |board| board.lookup(viewport, &reader, command, vantage.as_ref())); + let (resolved, bind) = match found { + Lookup::Fresh(resolved, bind) => (resolved, bind), + found => { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, if matches!(found, Lookup::Stale) { Resolve::Again } else { Resolve::New }); + let _ = found; + let (resolved, key) = resolve_as(ctx, &reader, command, vantage); + let (resolved, bind) = (Arc::new(resolved), key.bind()); + with(ctx, |board| board.keep(viewport, reader, Arc::clone(&resolved), key)); + (resolved, bind) + } + }; + note_read(ctx, bind); resolved } -/// `command` from the vantage of `reader`, and the key of the state it read. The readers' first resolution and the one -/// `begin` makes again both come from here. -fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef) -> (ResolvedCommand, Option) { +/// The vantage a layered reader is judged from: the window under its layer, or where focus goes once its menus close +/// (`None` when no stop is there). `None` for the other readers, which are judged from the board's own. +fn vantage_of(ctx: &Context, reader: &Reader) -> Option> { match reader { - Reader::Global => resolve_from(ctx, command, None), - Reader::Beneath(layer) => { - let from = beneath(ctx, *layer); - resolve_from(ctx, command, Some(&from)) - } - Reader::Chain(chain) => resolve_chain(ctx, command, chain), - Reader::InMenu(menu, chain) => { - let from = out_of_menu(ctx, *menu); - let instance = with(ctx, |board| { - board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, from.as_ref().unwrap_or(&board.here)).1) - }); - resolve_in(ctx, command, instance, Reach::Chain(chain), from.as_ref()) - } + Reader::Beneath(layer) => Some(Some(beneath(ctx, *layer))), + Reader::InMenu(menu, _) => Some(out_of_menu(ctx, *menu)), + Reader::Global | Reader::Chain(_) => None, } } -/// `command` against the instances of `chain`. -fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain) -> (ResolvedCommand, Option) { - let instance = with(ctx, |board| board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, &board.here).1)); - resolve_in(ctx, command, instance, Reach::Chain(chain), None) +/// `command` from the vantage of `reader` (`vantage`, from `vantage_of`), and the inputs it was made from. The +/// readers' first resolution and the one `begin` makes again both come from here. +fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef, vantage: Option>) -> (ResolvedCommand, ResolveKey) { + let from = vantage.as_ref().and_then(Option::as_ref); + let (resolved, mut key) = match reader { + Reader::Global | Reader::Beneath(_) => resolve_from(ctx, command, from), + Reader::Chain(chain) => resolve_chain(ctx, command, chain, None), + Reader::InMenu(_, chain) => resolve_chain(ctx, command, chain, from), + }; + key.vantage = vantage; + (resolved, key) } -fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, Option) { - let (_, instance) = with(ctx, |board| board.target_of(ctx, command, from.unwrap_or(&board.here))); - resolve_in(ctx, command, instance, Reach::Focus, from) +/// The instance a source with no component of its own delivers `command` to from `from`, noting in `reads` that it +/// read the focus when it picked one. +fn target_read(ctx: &Context, board: &Board, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> (bool, Option) { + let (app, instance) = board.target_of(ctx, command, from); + reads.focus |= !app; + (app, instance) } -/// fx.F23: resolves every command a reader of `viewport` was shown again, from that reader's own vantage under this -/// pass's gate, states, modal facts and instances, and notes an edit of the state key of each whose resolution differs -/// in any shown part (label, chord, enabled, checked, marked, hint), so a settled region that shows it runs; the entry -/// keeps the new resolution. Readers of regions that did not run keep their entries: a settled region is the reader -/// this exists for. It reads no input: a second pass of a frame compares against what the first pass's runs were shown -/// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal +/// `command` against the instances of `chain`, judged from `from` (`None`: the board's own vantage). +fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let instance = with(ctx, |board| { + board.innermost(chain, board.scope_of(command)).or_else(|| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads).1) + }); + resolve_in(ctx, command, instance, Reach::Chain(chain), from, reads) +} + +fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let (_, instance) = with(ctx, |board| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads)); + resolve_in(ctx, command, instance, Reach::Focus, from, reads) +} + +/// `command` resolved once, for a key press or a fire: nothing keeps it. +fn resolve_once(ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>) -> ResolvedCommand { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + resolve_in(ctx, command, instance, reach, from, Reads::default()).0 +} + +/// fx.F23: resolves again what a reader of `viewport` was shown when an input of it changed since the viewport's last +/// wake, from that reader's own vantage under this pass's gate, states, modal facts and instances, and notes an edit of +/// the key each was read under when its resolution differs in any shown part (label, chord, enabled, checked, marked, +/// hint), so a settled region that shows it runs; the entry keeps the new resolution. Readers of regions that did not +/// run keep their entries: a settled region is the reader this exists for. It walks only the entries whose inputs +/// moved, through the table's indexes: every entry when a generation all of them read moved (the shared one, the +/// viewport's keys, the gate), else the readers of the focus, of the focused stop's edits and of each changed state, +/// and the readers under a layer or in a menu, whose vantage it reads again. A second pass of a frame compares against +/// what the first pass's runs were shown, so it wakes only the readers whose resolution the first pass changed (a modal /// layer it opened or closed), once. fn wake_shown(ctx: &Context, viewport: ViewportId) { - let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); + let taken = with(ctx, |board| { + let now = + Woke { gens: board.gens, view: board.view_gens(viewport), state_seq: board.state_seq, gate: board.gate.as_ref().map(CommandGate::key) }; + let shown = board.shown.get(&viewport)?; + let woke = shown.woke; + if woke == Some(now) && shown.layered.is_empty() { + return None; + } + let all = woke.is_none_or(|woke| woke.gens.shared != now.gens.shared || woke.view.keys != now.view.keys || woke.gate != now.gate); + let mut walk: HashSet = if all { shown.entries.keys().copied().collect() } else { shown.layered.clone() }; + if let Some(woke) = woke.filter(|_| !all) { + if (woke.gens.focus, woke.view.focus) != (now.gens.focus, now.view.focus) { + walk.extend(&shown.by_focus); + } + if woke.view.edits != now.view.edits { + walk.extend(&shown.by_edits); + } + for (_, state) in board.state_log.iter().filter(|(seq, _)| *seq > woke.state_seq) { + walk.extend(shown.by_state.get(state).into_iter().flatten()); + } + } + Some((now, walk, board.shown.remove(&viewport)?)) + }); + let Some((now, walk, mut table)) = taken else { return }; let mut changed = Vec::new(); - for (key, readers) in &mut table { - // A reader beneath a layer or inside a menu that is no longer shown is gone with it. - readers.retain(|(reader, _)| match reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), - _ => true, + // A reader beneath a layer or inside a menu that is no longer shown is gone with it. + table.drop_where(|entry| entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer))); + let mut vantages: HashMap>> = HashMap::new(); + for id in walk { + let Some(entry) = table.entries.get_mut(&id) else { continue }; + #[cfg(feature = "testing")] + measure::count_wake_walk(ctx); + let vantage = match entry.reader.layer() { + Some(layer) => vantages.entry(layer).or_insert_with(|| vantage_of(ctx, &entry.reader)).clone(), + None => None, + }; + let fresh = with(ctx, |board| { + let gate = board.gate_answer(&entry.kept.resolved.command); + holds(&mut entry.kept.key, board.gens, board.view_gens(viewport), &board.revisions, gate, vantage.as_ref()) }); - for (reader, kept) in readers.iter_mut() { - // The gate is app code and may resolve commands itself, so no board lock is held here. - let (resolved, _) = resolve_as(ctx, reader, &kept.command); - if resolved != *kept { - *kept = resolved; - changed.push(*key); - } + if fresh { + continue; } + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::Again); + let (resolved, key) = resolve_as(ctx, &entry.reader, &entry.kept.resolved.command, vantage); + let was = entry.kept.key.bind(); + let resolved = if resolved == *entry.kept.resolved { + Arc::clone(&entry.kept.resolved) + } else { + changed.extend(was); + changed.extend(key.bind().filter(|bind| Some(*bind) != was)); + Arc::new(resolved) + }; + table.replace(id, Kept { resolved, key }); } - table.retain(|_, readers| !readers.is_empty()); + table.woke = Some(now); with(ctx, |board| { - // Reads the gate made while the entries were out of the board. - let added = board.shown.remove(&viewport).unwrap_or_default(); - for (key, readers) in added { - for (reader, resolved) in readers { - keep_in(table.entry(key).or_default(), reader, &resolved); + // Resolutions read nothing into the table while it is out of the board; keep any that arrived all the same. + if let Some(added) = board.shown.remove(&viewport) { + for (_, entry) in added.entries { + let number = entry.kept.key.number; + table.keep(entry.reader, number, entry.kept); } } - if !table.is_empty() { + if !table.entries.is_empty() { board.shown.insert(viewport, table); } }); - for (number, instance) in changed { - lazy::note_edit(ctx, BindKey::Command(number, instance)); + for key in changed { + lazy::note_edit(ctx, key); } } +/// Testing check, every 100th pass of a viewport: every kept resolution of `viewport` equals a full resolution from its +/// reader, and every kept gate answer equals the gate's answer asked again apart from the cache. A difference is an +/// input the keys miss. +#[cfg(feature = "testing")] +fn check_kept(ctx: &Context, viewport: ViewportId) { + let Some(table) = with(ctx, |board| board.shown.remove(&viewport)) else { return }; + for entry in table.entries.values() { + if entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer)) { + continue; + } + let command = &entry.kept.resolved.command; + measure::count_resolve(ctx, Resolve::Checked); + let (fresh, _) = resolve_as(ctx, &entry.reader, command, vantage_of(ctx, &entry.reader)); + assert!( + fresh == *entry.kept.resolved, + "the kept resolution of {} for a {} reader differs from a full resolve: kept {:?}, resolved {fresh:?}", + command, + entry.reader.kind(), + entry.kept.resolved, + ); + let (cached, gate) = with(ctx, |board| (board.gate_answers.get(command.key_text().as_ref()).copied(), board.gate.clone())); + if let (Some(cached), Some(gate)) = (cached, gate) { + assert!(cached == gate.allows(command), "the kept gate answer for {command} differs from the gate's"); + } + } + with(ctx, |board| { + board.shown.insert(viewport, table); + }); +} + /// Step-1 resolution for a context in `chain`; `None` when the command's scope has no instance in the chain. -pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option { +pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option> { let (found, app) = with(ctx, |board| { let scope = board.scope_of(command); (board.innermost(chain, scope).is_some(), board.to_app(scope)) @@ -1023,7 +1504,9 @@ fn queue(ctx: &Context, fired: Fired) { pub(crate) fn fall_through(ctx: &Context, command: craft_behavior::EditCommand) { let Some(command) = EditCommands::of(command) else { return }; let command = CommandRef::from(command); - let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here).0.instance); + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here, &mut Reads::default()).0.instance); let fired = Fired { target, ..Fired::new(command, FireSource::Key, FirePhase::Press, pass::now(ctx)) }; with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) }); repaint::request_of(ctx, ViewportId::ROOT); @@ -1059,7 +1542,7 @@ fn fire_in(ctx: &Context, command: &CommandRef, source: FireSource, from: Option if !app && instance.is_none() { return false; } - let (resolved, _) = resolve_in(ctx, command, instance, Reach::Focus, from); + let resolved = resolve_once(ctx, command, instance, Reach::Focus, from); if !resolved.enabled { return false; } @@ -1099,11 +1582,14 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef, let key = (number, Some(instance)); // The pass that publishes is the one that knows the layers around the caller. let in_modal = chain.ids().any(|id| board.is_modal_root(id)); - if in_modal { - board.modal_published.insert(key); + if in_modal && board.modal_published.insert(key) && !board.modal_published_last.contains(&key) { + board.gens.shared += 1; } let changed = !same_state(board.this.get(&key).or_else(|| board.last.get(&key)), Some(&state)); board.this.insert(key, state); + if changed { + board.bump_state(key); + } changed.then_some((number, instance)) }); if let Some((number, instance)) = changed { @@ -1165,7 +1651,7 @@ pub fn bound_around(ctx: &Context, at: Id, around: &CommandChain, S::from_ref(&hit.command)?; Some((hit.command, board.instance_around(at, around, S::SCOPE.name()))) })?; - let (resolved, _) = resolve_in(ctx, &command, instance, Reach::Chain(around), None); + let resolved = resolve_once(ctx, &command, instance, Reach::Chain(around), None); if resolved.enabled { S::from_ref(&command) } else { None } } @@ -1186,7 +1672,7 @@ pub(crate) fn binds_scoped(ctx: &Context, chord: &Chord) -> bool { let (_, instance) = board.target_of(ctx, &command, &board.here); Some((command, instance)) }); - found.is_some_and(|(command, instance)| resolve_in(ctx, &command, instance, Reach::Focus, None).0.enabled) + found.is_some_and(|(command, instance)| resolve_once(ctx, &command, instance, Reach::Focus, None).enabled) } /// Where a shortcut pressed with focus in a menu or on a menu bar matches, and where a hit gives the focus back. The @@ -1248,8 +1734,12 @@ pub(crate) fn begin(ctx: &Context) { // A shortcut pressed in a menu or on a menu bar matches where the focus returns to once the menus close. let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| Returning::of(ctx, focused)); let shell = frame::shell_root(ctx, viewport); + let edits = focused_edits(ctx, viewport); let taken = with(ctx, |board| { - board.held_open = held_open; + if board.held_open != held_open { + board.held_open = held_open; + board.gens.shared += 1; + } let returned = returning .map(Returning::id) .and_then(|held| [board.before.get(&viewport), board.chains.get(&viewport)].into_iter().flatten().find(|(id, _)| *id == held)) @@ -1262,18 +1752,42 @@ pub(crate) fn begin(ctx: &Context) { (true, Some(root)) => vec![*root], _ => chain, }; - if !chain.is_empty() { - board.last_focused.clone_from(&chain); + let view = board.views.entry(viewport).or_default(); + if !chain.is_empty() && view.last_focused != chain { + view.last_focused.clone_from(&chain); + view.gens.focus += 1; } // Nothing focused outside a modal: the window's shell root takes the commands, so a window command's key comes // before an app command's. Nothing holds focus there, so the chain last focused stays. let chain = if chain.is_empty() && focused.is_none() { shell.into_iter().collect() } else { chain }; match board.here.focused.iter_mut().find(|(v, _)| *v == viewport) { - Some(entry) => entry.1.clone_from(&chain), - None => board.here.focused.push((viewport, chain.clone())), + Some(entry) if entry.1 == chain => {} + Some(entry) => { + entry.1.clone_from(&chain); + board.gens.focus += 1; + } + None => { + board.here.focused.push((viewport, chain.clone())); + board.gens.focus += 1; + } } - board.here.dialog_keys = shortcuts.dialog; - board.here.inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + // The viewport's own facts move its own generations; `here` holds the running viewport's for the pass. + let inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + let view = board.views.entry(viewport).or_default(); + if view.dialog_keys != shortcuts.dialog { + view.dialog_keys = shortcuts.dialog; + view.gens.keys += 1; + } + if view.inside_modal != inside_modal { + view.inside_modal = inside_modal; + view.gens.focus += 1; + } + if view.edits != edits { + view.edits = edits; + view.gens.edits += 1; + } + board.here.dialog_keys = view.dialog_keys; + board.here.inside_modal.clone_from(&view.inside_modal); if shortcuts.keys.is_empty() { return None; } @@ -1289,6 +1803,10 @@ pub(crate) fn begin(ctx: &Context) { }); // With this pass's vantage set, what the readers were shown is resolved again before any of them runs. wake_shown(ctx, viewport); + #[cfg(feature = "testing")] + if pass::pass_nr(ctx, viewport).is_multiple_of(100) { + check_kept(ctx, viewport); + } let Some((keys, mut matcher)) = taken else { return }; let mut fired = Vec::new(); for shortcut in &shortcuts.keys { @@ -1316,7 +1834,7 @@ pub(crate) fn begin(ctx: &Context) { continue; }; let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here)); - let (resolved, _) = resolve_in(ctx, &hit.command, instance, Reach::Focus, None); + let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None); if !resolved.enabled { continue; } @@ -1369,9 +1887,22 @@ pub(crate) fn begin(ctx: &Context) { /// The end hook: instances that stopped registering are gone, and so are the commands queued for them and the readers /// inside them. pub(crate) fn end(ctx: &Context) { + let viewport = pass::current_viewport(ctx); with(ctx, |board| { let live = pass::live_viewports(ctx); let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); + // An instance of this viewport this pass did not register is dead from the viewport's next pass: resolutions + // see it. + let dies = board.instances.iter().zip(&alive).any(|(i, alive)| *alive && i.viewport == viewport && i.stamp < pass::pass_nr(ctx, viewport)); + let gone: HashSet = board.instances.iter().zip(&alive).filter(|(_, alive)| !**alive).map(|(i, _)| i.id).collect(); + // The revisions of a removed instance's states go in the same step as a shared move, which makes every entry + // that holds one stale first. + if !gone.is_empty() { + board.revisions.retain(|(_, instance), _| instance.is_none_or(|id| !gone.contains(&id))); + } + if dies || !gone.is_empty() { + board.gens.shared += 1; + } let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); let instances = &board.instances; @@ -1380,16 +1911,20 @@ pub(crate) fn end(ctx: &Context) { board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); + board.views.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); board.shown.retain(|viewport, table| { - table.retain(|_, readers| { - readers.retain(|(reader, _)| match reader { - Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), - _ => true, - }); - !readers.is_empty() + table.drop_where(|entry| match &entry.reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_some_and(|id| !ids(id)), + _ => false, }); - live.contains(viewport) && !table.is_empty() + live.contains(viewport) && !table.entries.is_empty() }); + // The state log keeps the changes no kept table has woken past. + let oldest = board.shown.values().map(|table| table.woke.map_or(0, |woke| woke.state_seq)).min(); + match oldest { + Some(oldest) => board.state_log.retain(|(seq, _)| *seq > oldest), + None => board.state_log.clear(), + } }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 3c9592467..d18815467 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -31,6 +31,7 @@ pub use board::{bound_around, take_around}; pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; +use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; use craft_behavior::edit_history::Step; use craft_keymap::{Chord, Overrides}; @@ -280,17 +281,72 @@ pub struct ResolvedCommand { /// The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an /// operation is pending. A command the gate refuses resolves disabled and does not fire. +/// +/// The gate is a `fn` of its props, as a memoized view's `show` is: the props hold everything the gate reads, so the +/// runtime asks it once per command while the props' key stays the same, and again only when it changes. #[derive(Clone)] -pub struct CommandGate(Arc bool + Send + Sync>); +pub struct CommandGate { + key: u128, + allows: Arc bool + Send + Sync>, +} impl CommandGate { - /// A gate that lets `allows` commands through. - pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self { - CommandGate(Arc::new(allows)) + /// A gate that lets through the commands `allows` accepts under `props`. + pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self { + let mut key = MemoKey::new(); + key.feed_hash(&std::any::TypeId::of::

()); + key.write(&(allows as usize).to_le_bytes()); + props.key(&mut key); + CommandGate { key: key.finish(), allows: Arc::new(move |command| allows(&props, command)) } + } + + /// The key of the gate's props and `fn`: equal keys give equal answers. + pub(crate) fn key(&self) -> u128 { + self.key } pub(crate) fn allows(&self, command: &CommandRef) -> bool { - (self.0)(command) + (self.allows)(command) + } +} + +/// The app-scope command states an app holds, in a [`Tracked`] it hands to [`CommandInput::states`] every frame. The +/// runtime reads them again only when the revision moves. +#[derive(Clone, Debug, Default, PartialEq, PlainData)] +pub struct CommandStates { + #[plain_data(assume = "command refs and states are plain values; the list is copied on write")] + states: Arc>, +} + +impl CommandStates { + /// No states. + pub fn new() -> Self { + CommandStates::default() + } + + /// Gives `command` `state`, in place of the state it had. + pub fn set(&mut self, command: impl Into, state: CommandState) { + let command = command.into(); + let states = Arc::make_mut(&mut self.states); + match states.iter_mut().find(|(held, _)| *held == command) { + Some((_, held)) => *held = state, + None => states.push((command, state)), + } + } + + /// Removes the state of `command`, which then resolves with its own label, enabled. + pub fn remove(&mut self, command: &CommandRef) -> Option { + let at = self.states.iter().position(|(held, _)| held == command)?; + Some(Arc::make_mut(&mut self.states).remove(at).1) + } + + /// The state of `command`. + pub fn get(&self, command: &CommandRef) -> Option<&CommandState> { + self.states.iter().find(|(held, _)| held == command).map(|(_, state)| state) + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.states.iter() } } @@ -298,7 +354,7 @@ impl CommandGate { #[derive(Clone, Default)] #[non_exhaustive] pub struct CommandInput { - pub(crate) states: Vec<(CommandRef, CommandState)>, + pub(crate) states: Option<(Revision, CommandStates)>, pub(crate) overrides: Option>, pub(crate) gate: Option, pub(crate) catalog: Option, @@ -310,10 +366,11 @@ impl CommandInput { CommandInput::default() } - /// The state of an app-scope command. + /// The app-scope command states the app holds. The runtime keeps the revision and reads the states again only + /// when it moves. #[must_use] - pub fn state(mut self, command: impl Into, state: CommandState) -> Self { - self.states.push((command.into(), state)); + pub fn states(mut self, states: &Tracked) -> Self { + self.states = Some((states.revision(), (**states).clone())); self } @@ -331,8 +388,8 @@ impl CommandInput { self } - /// The one gate over commands. It answers from what the app knew before the frame: the runtime asks it once per - /// command per frame, whichever components and passes resolve the command. + /// The one gate over commands. The runtime asks it once per command while the gate's props keep their key, whichever + /// components, passes and frames resolve the command. #[must_use] pub fn gate(mut self, gate: CommandGate) -> Self { self.gate = Some(gate); @@ -438,7 +495,7 @@ pub trait Commands: CommandAccess { /// `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above /// the context, and the enabled state of its instance. `None` when the command is scoped and no instance of its /// scope is above the context. - fn resolve_command(&self, command: impl Into) -> Option { + fn resolve_command(&self, command: impl Into) -> Option> { board::resolve_scoped(self.command_ctx(), self.command_chain(), &command.into()) } } @@ -457,7 +514,7 @@ pub fn fire(ctx: &Context, command: impl Into, source: FireSource) - /// `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state /// and hint, against the instance that [`fire`] would deliver it to. A scoped command with no live instance /// resolves disabled. -pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve(ctx: &Context, command: impl Into) -> Arc { board::resolve_global(ctx, &command.into()) } @@ -485,7 +542,7 @@ pub fn holder(ctx: &Context, chord: &Chord) -> Option { /// once the layer closes: for a surface that closes before its command runs (the command palette), whose own layer /// does not block the command. Outside a modal layer it is [`resolve`]. #[doc(hidden)] -pub fn resolve_beneath(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve_beneath(ctx: &Context, command: impl Into) -> Arc { match crate::runtime::overlay::modal_drawing(ctx) { Some(layer) => board::resolve_beneath(ctx, layer, &command.into()), None => resolve(ctx, command), diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c5f87706f..386f89f21 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -137,6 +137,45 @@ fn window_focus_facts(ctx: &Context, events: &[Event], native_pixels_per_point: #[derive(Default)] struct WindowFocus(Option); +/// The child windows of the root that are open: each opens with its first frame and stays listed in every frame's +/// viewports, as eframe lists every open viewport, until a test closes it ([`close_viewport`]) or the app sends it +/// `ViewportCommand::Close`. +#[derive(Default)] +struct OpenChildren(Vec); + +/// The open child windows, with `viewport` opened first when it is a child. +fn open_children(ctx: &Context, viewport: egui::ViewportId) -> Vec { + Service::::run(ctx, |open| { + if viewport != egui::ViewportId::ROOT && !open.0.contains(&viewport) { + open.0.push(viewport); + } + open.0.clone() + }) +} + +/// One run of `ui` on `input`; a root pass declares the open `children` after it, as an eframe app shows each of its +/// windows every frame: egui keeps a child viewport only while its parent's passes show it. Each child's content runs +/// in its own frames, so the declaration shows nothing. +fn run_ui(ctx: &Context, input: RawInput, children: &[egui::ViewportId], mut ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let root = input.viewport_id == egui::ViewportId::ROOT; + ctx.run_ui(input, |top| { + ui(top); + if root && !children.is_empty() { + let embedded = ctx.embed_viewports(); + ctx.set_embed_viewports(false); + for child in children { + ctx.show_viewport_deferred(*child, egui::ViewportBuilder::default(), |_, _| {}); + } + ctx.set_embed_viewports(embedded); + } + }) +} + +/// Closes the child window `viewport`: later frames no longer list it. +pub(crate) fn close_viewport(ctx: &Context, viewport: egui::ViewportId) { + Service::::run(ctx, |open| open.0.retain(|held| *held != viewport)); +} + /// The fixture's reset bridge, as egui-winit keeps one per window: the reset request it holds for each viewport, and /// the requests it dropped, which the next frame reports as `Event::ImeResetRetired`. #[derive(Default)] @@ -187,7 +226,8 @@ impl ImeResets { } /// Runs one pass of `viewport` at `time` seconds with `events` and `files`, on a window of `native_pixels_per_point` -/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live. +/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live; the +/// child stays open in every later frame, the root's included, until it is closed. #[expect(clippy::too_many_arguments, reason = "the arguments are the facts of one frame, and every caller passes them all")] pub(crate) fn run_frame( ctx: &Context, @@ -204,9 +244,10 @@ pub(crate) fn run_frame( let dropped_files = files.dropped.iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); Service::::run(ctx, |resets| resets.input(viewport, &mut events)); let mut viewports = window_focus_facts(ctx, &events, native_pixels_per_point); - if viewport != egui::ViewportId::ROOT { + let children = open_children(ctx, viewport); + for child in &children { viewports - .insert(viewport, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); + .insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); } let input = RawInput { screen_rect: Some(screen), @@ -218,7 +259,7 @@ pub(crate) fn run_frame( viewports, ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let mut output = drive(|| run_ui(ctx, input, &children, ui)); Service::::run(ctx, |resets| resets.output(viewport, &output.platform_output)); let mut flat = Vec::new(); for clipped in &output.shapes { @@ -257,6 +298,15 @@ pub(crate) fn run_frame( }) .collect(); let closed = output.viewport_output.values().any(|viewport| viewport.commands.iter().any(|command| matches!(command, ViewportCommand::Close))); + let closing: Vec = output + .viewport_output + .iter() + .filter(|(id, out)| **id != egui::ViewportId::ROOT && out.commands.iter().any(|command| matches!(command, ViewportCommand::Close))) + .map(|(id, _)| *id) + .collect(); + for child in closing { + close_viewport(ctx, child); + } let repaint_delay = output.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay); let copied = output .platform_output @@ -366,8 +416,14 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions { /// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened. pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec { let screen = Rect::from_min_size(Pos2::ZERO, screen); - let input = RawInput { screen_rect: Some(screen), time: Some(time), ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let children = open_children(ctx, egui::ViewportId::ROOT); + let mut viewports = egui::ViewportIdMap::default(); + viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default()); + for child in &children { + viewports.insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..egui::ViewportInfo::default() }); + } + let input = RawInput { screen_rect: Some(screen), time: Some(time), viewports, ..RawInput::default() }; + let mut output = drive(|| run_ui(ctx, input, &children, ui)); output.textures_delta.clear(); let mut flat = Vec::new(); for clipped in output.shapes { diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 71e2cf685..969020d63 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -297,6 +297,43 @@ pub fn chord_texts(ctx: &Context) -> u32 { last_totals(ctx, |log| log.chord_texts, 0) } +/// What a command resolution was for. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Resolve { + /// A resolution nothing kept: a reader's first, or one for a key press or a fire. + New, + /// A kept resolution made again because an input of it changed. + Again, + /// A kept resolution compared with a full one by the testing check every 100th pass. + Checked, +} + +/// Counts a command resolution in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_resolve(ctx: &Context, what: Resolve) { + totals(ctx, |log| log.resolves[what as usize] += 1); +} + +/// The command resolutions of the last pass of kind `what`. +#[cfg(feature = "testing")] +pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 { + last_totals(ctx, |log| log.resolves[what as usize], 0) +} + +/// Counts a kept resolution a wake walked to compare its key. +#[cfg(feature = "testing")] +pub(crate) fn count_wake_walk(ctx: &Context) { + totals(ctx, |log| log.wake_walks += 1); +} + +/// The kept resolutions the wakes of the last pass walked. +#[cfg(feature = "testing")] +pub fn last_pass_wake_walks(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.wake_walks, 0) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { @@ -362,29 +399,49 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { /// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] -pub(crate) struct PassTotals { +pub(crate) struct Totals { pass: u64, key_bytes: usize, text_layouts: u32, chord_texts: u32, + resolves: [u32; 3], + wake_walks: u32, asks: Vec<(&'static str, u32)>, } +/// The totals of the running pass and of the one before it, which a pass's own counting does not overwrite: a pass +/// that counts in its begin hook keeps the last pass readable. #[cfg(feature = "testing")] -fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { +#[derive(Default)] +pub(crate) struct PassTotals { + current: Totals, + previous: Totals, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut Totals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); pass_state::with::(ctx, |log| { - if log.pass != pass { - *log = PassTotals { pass, ..PassTotals::default() }; + if log.current.pass != pass { + let current = std::mem::replace(&mut log.current, Totals { pass, ..Totals::default() }); + log.previous = current; } - f(log) + f(&mut log.current) }) } #[cfg(feature = "testing")] -fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { +fn last_totals(ctx: &Context, f: impl FnOnce(&Totals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| { + if log.current.pass == last { + f(&log.current) + } else if log.previous.pass == last { + f(&log.previous) + } else { + none + } + }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 4b3cf72e1..ca91aecb4 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -25,6 +25,8 @@ pub(crate) enum BindKey { Record(Id), /// A command's state on the board: the command's number and the instance whose state it is, `None` for the app's. Command(u32, Option), + /// A command the focused stop answers for (an edit it takes): the command's number. + FocusedEdit(u32), } /// One measure a reader made from the value it read: what it was offered and the size it took. diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index aff8228e8..5065b8d83 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -2,8 +2,9 @@ use super::Frames; use super::story::{Story, StoryData, StoryOutput}; +use crate::contract::Tracked; use crate::runtime::access::Role; -use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState}; +use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState, CommandStates}; use crate::runtime::egui::access::{AccessTree, NodeKey}; use crate::runtime::egui::fixture::{self, AccessActionKind}; use crate::runtime::egui::injected; @@ -114,6 +115,8 @@ pub struct Fixture { show: Box, root: RootEnv, commands: CommandInput, + /// The app-scope command states, held as an app holds them. + states: Tracked, room: Vec2, tree: AccessTree, shown: Rect, @@ -153,6 +156,7 @@ impl Fixture { show: Box::new(show), root: RootEnv::default(), commands: CommandInput::new(), + states: Tracked::default(), room: Vec2::new(400.0, 300.0), tree: AccessTree::none(), shown: Rect::NOTHING, @@ -203,7 +207,8 @@ impl Fixture { fixture.data = data; fixture.outputs = outputs; fixture.root_id = root_id; - fixture.commands = Story::command_input([story]); + fixture.states = Tracked::new(Story::command_states([story])); + fixture.commands = CommandInput::new().states(&fixture.states); fixture.frames.commands(fixture.commands.clone()); fixture } @@ -230,9 +235,8 @@ impl Fixture { /// Gives app-scope `command` this state in every following pass, as an app's `FrameInput.commands` does; a later /// call for the same command replaces the earlier one. pub fn command_state(&mut self, command: impl Into, state: CommandState) -> &mut Self { - let command = command.into(); - self.commands.states.retain(|(held, _)| *held != command); - self.commands.states.push((command, state)); + self.states.set(command, state); + self.commands = self.commands.clone().states(&self.states); self.frames.commands(self.commands.clone()); self } diff --git a/crates/ui-contract/src/testing/frames.rs b/crates/ui-contract/src/testing/frames.rs index 0b27e14fe..938170f56 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -186,9 +186,13 @@ impl Frames { } /// One frame of `viewport`, a child window of the root while the root stays live, with `events`; `ui` runs once - /// per pass. Returns the number of passes. + /// per pass. Returns the number of passes. The child opens with its first frame and stays open, listed in the root's + /// frames too, until [`close_viewport`](Self::close_viewport) or a `ViewportCommand::Close` for it. pub fn frame_in_viewport(&mut self, viewport: egui::ViewportId, events: Vec, mut ui: impl FnMut(&mut Ui)) -> usize { - set_input(&self.ctx, self.input()); + // The app's input is the root's, once per app frame: a child window's frame runs inside it. + if viewport == egui::ViewportId::ROOT { + set_input(&self.ctx, self.input()); + } let mut passes = 0; self.run(viewport, events, |root| { passes += 1; @@ -253,6 +257,11 @@ impl Frames { self.time += seconds; } + /// Closes the child window `viewport`, as its user would: later frames no longer list it. + pub fn close_viewport(&mut self, viewport: egui::ViewportId) { + fixture::close_viewport(&self.ctx, viewport); + } + /// `n` frames with no events. pub fn idle(&mut self, n: usize, mut ui: impl FnMut(&mut Ui)) { for _ in 0..n { diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index d58471713..a93c9c42b 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -2,7 +2,7 @@ use super::Fixture; use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec}; -use crate::runtime::commands::CommandInput; +use crate::runtime::commands::CommandStates; use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value}; use egui::{Id, Response, Ui, Vec2}; use std::any::{Any, TypeId}; @@ -102,9 +102,9 @@ pub struct Story { pub drive: Drive, /// The reason a disabled control shows (`disabled_text` of its tooltip), when the story gives its control one. pub disabled_text: Option<&'static str>, - /// Adds this story's app-scope command states to the frame's command input; runners fold the shown stories' - /// functions over `CommandInput::new()` before the first frame. - pub commands: Option CommandInput>, + /// Sets this story's app-scope command states; runners apply the shown stories' functions in order to one + /// `CommandStates` before the first frame and hold it as the app's. + pub commands: Option, /// The caption a viewer shows over the story; `None` for the title made of its name (`contract::story_title`). pub title: Option<&'static str>, /// The group a viewer shows the story in, with the other stories of the type that name it, as the cases of one @@ -118,16 +118,20 @@ impl Story { Story { name, covers: &[], show, drive: Drive::Auto, disabled_text: None, commands: None, title: None, group: None } } - /// Sets the function that adds the story's command states to the frame's command input. - pub const fn commands(mut self, add: fn(CommandInput) -> CommandInput) -> Self { + /// Sets the function that sets the story's app-scope command states. + pub const fn commands(mut self, add: fn(&mut CommandStates)) -> Self { self.commands = Some(add); self } - /// The command input of `stories` shown together: each story's command function applied in order over an empty - /// input, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. - pub fn command_input<'a>(stories: impl IntoIterator) -> CommandInput { - stories.into_iter().filter_map(|story| story.commands).fold(CommandInput::new(), |input, add| add(input)) + /// The command states of `stories` shown together: each story's command function applied in order to empty + /// states, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. + pub fn command_states<'a>(stories: impl IntoIterator) -> CommandStates { + let mut states = CommandStates::new(); + for add in stories.into_iter().filter_map(|story| story.commands) { + add(&mut states); + } + states } /// The caption a viewer shows over the story. diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 78eea00a9..16ae912b5 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -94,9 +94,9 @@ enum Shown { Apply, } -/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new closure. +/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new gate. fn gate(refuses: bool) -> CommandInput { - CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| !refuses || Shown::from_ref(command).is_none())) + CommandInput::new().gate(CommandGate::new(refuses, |refuses: &bool, command: &CommandRef| !*refuses || Shown::from_ref(command).is_none())) } /// A modal layer with an empty body. diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index 1be5fbced..8fc707763 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -9,10 +9,11 @@ use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, PanelId, use craft_behavior::dock::{PanelState, Workspace as Dock}; use craft_theme::AppSizes; use craft_theme_editor::{ThemeSubject, parse_sizes}; -use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _}; +use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _, Tracked}; use craft_ui::docking::DockConfig; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; +use craft_ui::runtime::commands::{CommandInput, CommandStates}; use craft_ui::runtime::drag::OsFile; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::{FrameInput, FrameOutput}; @@ -34,6 +35,9 @@ pub struct Gallery { noted: HashSet, /// A command changed the viewer since the settings were last compared. command_ran: bool, + /// The app-scope command states of the front component's stories, and that component: rebuilt only when another + /// component comes to the front, so an idle frame keeps one revision. + command_states: (Option<&'static str>, Tracked), } impl Gallery { @@ -45,7 +49,7 @@ impl Gallery { /// The viewer of `catalog` over `persisted`. pub fn new(catalog: Catalog, persisted: Persisted) -> Self { let viewer = Viewer::new(catalog, persisted.get()); - Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false } + Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false, command_states: (None, Tracked::default()) } } /// Shows what the settings and a dropped file have to say, once each, as toasts. @@ -143,10 +147,14 @@ impl ShellApp for Gallery { // App-scope command states are one input per frame, so only the stories of the component shown reach it; the // Overview, the Theme dock and a frame with no such tab give none. let browser = &self.viewer.browser; - let stories = front_component(&self.viewer) - .into_iter() - .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); - FrameInput::new(self.viewer.env.clone()).commands(craft_ui::testing::Story::command_input(stories)) + let front = front_component(&self.viewer); + if front != self.command_states.0 { + let stories = front + .into_iter() + .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); + self.command_states = (front, Tracked::new(craft_ui::testing::Story::command_states(stories))); + } + FrameInput::new(self.viewer.env.clone()).commands(CommandInput::new().states(&self.command_states.1)) } fn output(&mut self, output: FrameOutput) { diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 2cc3757c7..dfa079698 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -212,7 +212,7 @@ fn pick(ui: &Ui, state: &mut MockState, tool: Tool, step: PickStep) { /// Makes `tool` the current tool and says so in the status bar. fn select(ui: &Ui, state: &mut MockState, tool: Tool) { state.tool = tool; - let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label; + let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label.clone(); let text = Env::of(ui).words::().tool_status.fill(&[("tool", &*name)]); state.status = Some(StatusMessage::new(text)); } diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 7db0607d2..761eb0d93 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -223,7 +223,7 @@ impl Parse for StoryArgs { /// reason to show while disabled, which the story takes from `StoryData::tooltip`. `title = ".."` is the caption a /// viewer shows over the story. `group = ".."` puts the story in a named group with the type's other stories that /// name it, in declaration order; a viewer shows a group together, each story under its caption. -/// `commands = ` names a `fn(CommandInput) -> CommandInput` that sets the command states the story runs under. +/// `commands = ` names a `fn(&mut CommandStates)` that sets the app-scope command states the story runs under. /// The type's registration and the story meet by the type's registered name. #[proc_macro_attribute] pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream { diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index 833ba59a8..bef693ce6 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -167,11 +167,11 @@ enum DrawerKey { /// headings. struct Rows<'a> { keys: Vec, - resolved: &'a [Vec], + resolved: &'a [Vec>], } impl<'a> Rows<'a> { - fn new(resolved: &'a [Vec]) -> Self { + fn new(resolved: &'a [Vec>]) -> Self { let mut keys = Vec::new(); for (group, tools) in resolved.iter().enumerate().filter(|(_, tools)| !tools.is_empty()) { keys.push(DrawerKey::Group(group)); @@ -221,7 +221,7 @@ impl ToolbarDrawer<'_, T> { let words = env.words::(); let os = os_of(ui.ctx()); let ctx = ui.ctx().clone(); - let resolved: Vec> = + let resolved: Vec>> = groups.iter().map(|group| group.tools.iter().map(|tool| commands::resolve(&ctx, tool.command.clone())).collect()).collect(); let mut edits: Vec> = dropped.and_then(|dropped| drop_edit(dropped.drag, dropped.at, groups, toolbar)).into_iter().collect(); let mut select: Option = None; diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index dda5a9c5f..9bc9aab91 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -90,9 +90,9 @@ struct Held(bool); /// What the parts step resolved for the tools this pass. struct Laid { - resolved: Vec>, + resolved: Vec>>, /// The click command as resolved, when the button has one. - click: Option, + click: Option>, shown: usize, } @@ -185,7 +185,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { /// The command the face stands for: the click command when there is one, else the shown tool's. fn lead<'l>(&self, laid: &'l Laid) -> Option<&'l ResolvedCommand> { - if self.click.is_some() { laid.click.as_ref() } else { laid.resolved.get(laid.shown).and_then(Option::as_ref) } + if self.click.is_some() { laid.click.as_deref() } else { laid.resolved.get(laid.shown).and_then(Option::as_deref) } } } diff --git a/crates/ui-patterns/src/patterns/panels/palette/stories.rs b/crates/ui-patterns/src/patterns/panels/palette/stories.rs index da81dbb08..c15197308 100644 --- a/crates/ui-patterns/src/patterns/panels/palette/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/palette/stories.rs @@ -3,7 +3,7 @@ use super::CommandPalette; use crate::contract::Bind; use crate::menu::search::HelpEntry; -use crate::runtime::commands::{CommandInput, CommandRef, CommandState, EditCommands}; +use crate::runtime::commands::{CommandRef, CommandState, CommandStates, EditCommands}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::sync::LazyLock; @@ -69,8 +69,8 @@ fn palette(ui: &mut Ui, data: &mut StoryData, recents: Vec) -> Story } /// The command states the stories run under: Redo is disabled, as the entries list it. -fn commands(input: CommandInput) -> CommandInput { - input.state(EditCommands::Redo, CommandState::new().enabled(false)) +fn commands(states: &mut CommandStates) { + states.set(EditCommands::Redo, CommandState::new().enabled(false)); } #[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "PhotoCraft", commands = commands)] diff --git a/crates/ui-shell/tests/it/commands/app_catalog.rs b/crates/ui-shell/tests/it/commands/app_catalog.rs index ef6ecaff4..d8e3a6b03 100644 --- a/crates/ui-shell/tests/it/commands/app_catalog.rs +++ b/crates/ui-shell/tests/it/commands/app_catalog.rs @@ -2,9 +2,10 @@ //! rules every app command follows, and a frame builds a keymap only for a catalog generation it has not built. // The catalog is given through `Frames::commands`, which keeps it for every later frame. -use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::contract::{Bind, Props as _, Show as _, Tracked}; use craft_ui::runtime::commands::{ - AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, EditCommands, FirePhase, Scope, keymap_builds, + AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, CommandStates, EditCommands, FirePhase, Scope, + keymap_builds, }; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::take_output; @@ -198,11 +199,9 @@ fn a_press_without_a_physical_key_fires_its_command_once() { fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() { let cut = CommandRef::from(EditCommands::Cut); let alternate = CommandDef::new(cut.clone(), "Cut", Scope::app()).with_default(Binding::parse("F2").expect("the trial's chord parses")); - let input = || { - CommandInput::new() - .catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")) - .state(cut.clone(), CommandState::new()) - }; + let mut states = Tracked::new(CommandStates::new()); + states.set(cut.clone(), CommandState::new()); + let input = || CommandInput::new().catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")).states(&states); let mut show = |ui: &mut Ui| { AppShell::new(WindowKey::main()).show(ui, &mut ()); }; diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index d4bb19304..2b5beb33a 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,8 +1,6 @@ use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; -use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve, -}; +use craft_ui::runtime::commands::{CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve}; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; use craft_ui::runtime::measure::chord_texts; @@ -82,58 +80,6 @@ fn an_enclosing_scopes_shortcut_beats_the_applications() { assert_eq!((closed.get(), ids(&take_output(&frames.ctx).fired)), (1, vec!["trial.jump"]), "outside the dock the application's command fires"); } -/// 1.8 and 7.2: the gate is app code, so it runs with no runtime lock held and may use the board. -#[trial] -fn the_gate_may_resolve_commands() { - let mut frames = Frames::new(); - let ctx = frames.ctx.clone(); - let inside = std::sync::atomic::AtomicBool::new(false); - frames.commands(CommandInput::new().gate(CommandGate::new(move |_: &CommandRef| { - // The nested `resolve` runs the gate again, which stops here. - inside.swap(true, std::sync::atomic::Ordering::SeqCst) || { - let enabled = resolve(&ctx, AppCommand::Go).enabled; - inside.store(false, std::sync::atomic::Ordering::SeqCst); - enabled - } - }))); - let mut show = |ui: &mut Ui| { - Tap::new().id_salt("go").command(AppCommand::Save).show(ui); - }; - frames.idle(2, &mut show); - frames.frame(vec![key_press(Key::K, Modifiers::COMMAND)], &mut show); - assert_eq!(ids(&take_output(&frames.ctx).fired), ["trial.save"]); -} - -/// The gate answers from what the app knew before the frame: a frame asks it once per command, however many components -/// show the command and however many passes and readers resolve it. -#[trial] -fn a_frame_asks_the_gate_once_per_command() { - use std::sync::{Arc, Mutex}; - let asked = Arc::new(Mutex::new(Vec::::new())); - let log = Arc::clone(&asked); - let mut frames = Frames::new(); - frames.commands(CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| { - log.lock().expect("the gate's log").push(command.key()); - true - }))); - let mut show = |ui: &mut Ui| { - for salt in ["a", "b", "c"] { - Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); - } - }; - frames.idle(2, &mut show); - for at in [5.0, 6.0, 7.0] { - asked.lock().expect("the gate's log").clear(); - frames.frame(vec![moved(Pos2::new(at, at))], &mut show); - let asked = asked.lock().expect("the gate's log").clone(); - let mut once = asked.clone(); - once.sort(); - once.dedup(); - assert!(once.contains(&"trial.save".to_owned()), "the frame resolves the taps' command: {asked:?}"); - assert_eq!(asked.len(), once.len(), "a frame asked the gate for a command twice: {asked:?}"); - } -} - /// 11.3: a scoped entry waits for its instance and is dropped when the instance stops being live. #[trial] fn an_untaken_scoped_entry_is_dropped_with_its_instance() { diff --git a/crates/ui-shell/tests/it/commands/mod.rs b/crates/ui-shell/tests/it/commands/mod.rs index 3c8a37d28..0df0ca31e 100644 --- a/crates/ui-shell/tests/it/commands/mod.rs +++ b/crates/ui-shell/tests/it/commands/mod.rs @@ -4,3 +4,4 @@ mod app_catalog; mod app_scope; mod board; mod kit; +mod resolve; diff --git a/crates/ui-shell/tests/it/commands/resolve.rs b/crates/ui-shell/tests/it/commands/resolve.rs new file mode 100644 index 000000000..955bc8677 --- /dev/null +++ b/crates/ui-shell/tests/it/commands/resolve.rs @@ -0,0 +1,384 @@ +//! Command resolution runs only when an input of it changed: count trials over fifty shown commands. + +use super::kit::{AppCommand, DOCK, Dock, PANE, Pane, PaneCommand, Tap}; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Lazy, Trigger}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Tracked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Commands as _, Scope, +}; +use craft_ui::runtime::commands::{EditCommands, declare_child, resolve, resolve_beneath}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::runtime::measure::last_pass_wake_walks; +use craft_ui::runtime::measure::{Resolve, last_pass_resolves}; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::pointer::{press, release}; +use craft_ui::testing::{Frames, trial}; +use craft_ui::text::TextField; +use egui::{Id, Pos2, Ui}; +use egui::{Key, Modifiers, ViewportId}; +use std::cell::{Cell, RefCell}; + +/// The panes: each is an instance of the pane scope, so each is its own reader of the commands its taps show. +const PANES: [&str; 5] = ["a", "b", "c", "d", "e"]; + +/// The commands the taps of a pane show, each by two taps. +fn shown(at: usize) -> CommandRef { + match at % 5 { + 0 => AppCommand::Save.into(), + 1 => AppCommand::Go.into(), + 2 => AppCommand::Play.into(), + 3 => AppCommand::Jump.into(), + _ => PaneCommand::ZoomIn.into(), + } +} + +/// Readers kept: one per pane and command. +const KEPT: u32 = 25; +/// Readers of Save: one per pane. +const SAVE_READERS: u32 = 5; +/// Distinct commands shown. +const COMMANDS: u32 = 5; + +/// Fifty taps in five panes; pane `a` publishes Zoom In enabled as `zoom` says. `ids` gets each tap's id. With +/// `global`, a surface with no component of its own reads Zoom In after the panes, which picks an instance by the focus. +struct Scene { + zoom: Cell, + ids: RefCell>, + global: bool, + /// Pane `a` is left out of the next pass. + skip_a: Cell, + /// Salts the panes' ids, so two windows show panes of their own. + window: &'static str, +} + +impl Scene { + fn new() -> Self { + Scene { zoom: Cell::new(true), ids: RefCell::new(Vec::new()), global: false, skip_a: Cell::new(false), window: "" } + } + + fn show(&self, ui: &mut Ui) { + self.ids.borrow_mut().clear(); + let skip_a = self.skip_a.replace(false); + for (pane, salt) in PANES.iter().enumerate() { + if pane == 0 && skip_a { + continue; + } + Pane::new().id_salt((self.window, *salt)).show(ui, |ui, cx| { + if pane == 0 { + cx.publish(PaneCommand::ZoomIn, CommandState::new().enabled(self.zoom.get())); + } + for at in 0..10 { + let id = Tap::new().id_salt(at).command(shown(at)).show(ui).id; + self.ids.borrow_mut().push(id); + } + }); + } + if self.global { + resolve(ui.ctx(), PaneCommand::ZoomIn); + } + } +} + +fn counts(ctx: &egui::Context) -> (u32, u32) { + (last_pass_resolves(ctx, Resolve::New), last_pass_resolves(ctx, Resolve::Again)) +} + +/// One frame of `scene`, and its new and repeated resolutions summed over every pass of the frame: each pass after +/// the first reads the one before it as it starts, and the last is read after the frame. +fn frame(frames: &mut Frames, scene: &Scene) -> (u32, u32) { + let (new, again, _) = frame_walks(frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + (new, again) +} + +/// One frame of `viewport` running `show`, and its new and repeated resolutions and the kept resolutions its wakes +/// walked, summed over every pass of the frame. +fn frame_walks(frames: &mut Frames, viewport: ViewportId, show: &mut dyn FnMut(&mut Ui)) -> (u32, u32, u32) { + let ctx = frames.ctx.clone(); + let (mut new, mut again, mut walks, mut pass) = (0, 0, 0, 0); + let mut add = |ctx: &egui::Context| { + let (n, a) = counts(ctx); + (new, again, walks) = (new + n, again + a, walks + last_pass_wake_walks(ctx)); + }; + frames.frame_in_viewport(viewport, vec![], |ui| { + if pass > 0 { + add(&ctx); + } + pass += 1; + show(ui); + }); + add(&ctx); + (new, again, walks) +} + +thread_local! { + static ASKS: Cell = const { Cell::new(0) }; +} + +/// The gate: refuses Save while `refuses`; counts its asks. +fn refuse_save(refuses: &bool, command: &CommandRef) -> bool { + ASKS.with(|asks| asks.set(asks.get() + 1)); + !(*refuses && AppCommand::from_ref(command) == Some(AppCommand::Save)) +} + +fn gated(states: &Tracked, refuses: bool) -> CommandInput { + CommandInput::new().states(states).gate(CommandGate::new(refuses, refuse_save)) +} + +/// An idle frame with fifty shown commands resolves nothing, and neither does a pointer move over none of them. +#[trial] +fn an_idle_frame_resolves_no_command() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + assert_eq!(scene.ids.borrow().len(), 50, "fifty commands are shown"); + assert_eq!(frames.frame(vec![], |ui| scene.show(ui)), 1, "an idle frame takes one pass"); + assert_eq!(counts(&frames.ctx), (0, 0), "an idle frame resolves nothing"); + assert_eq!(frames.frame(vec![moved(Pos2::new(900.0, 900.0))], |ui| scene.show(ui)), 1, "so does a pointer move"); + assert_eq!(counts(&frames.ctx), (0, 0), "a pointer move away from the taps resolves nothing"); +} + +/// Two windows with frames alternating between them, idle: each frame resolves nothing and walks nothing, as the +/// child stays open across the root's frames and the root's across the child's. +#[trial] +fn idle_frames_alternating_between_two_windows_resolve_nothing() { + let root = Scene::new(); + let other = Scene { window: "child", ..Scene::new() }; + let child = ViewportId::from_hash_of("second window"); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + for _ in 0..3 { + frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)); + frame_walks(&mut frames, child, &mut |ui| other.show(ui)); + } + for round in 0..4 { + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)), (0, 0, 0), "root frame {round}"); + assert_eq!(frame_walks(&mut frames, child, &mut |ui| other.show(ui)), (0, 0, 0), "child frame {round}"); + } +} + +/// Editing one app-scope state resolves again only that command's readers, once. +#[trial] +fn one_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + states.set(AppCommand::Save, CommandState::new().enabled(false)); + frames.commands(gated(&states, false)); + assert_eq!( + frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), + (0, SAVE_READERS, SAVE_READERS), + "the wake walks and resolves again only Save's readers" + ); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "the next frame walks nothing"); +} + +/// An instance publishing a new state resolves again only the readers of that instance's state. +#[trial] +fn a_published_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + scene.zoom.set(false); + // The publish runs before its reader, which resolves again as it reads; a wake walks only that reader. + let (new, again, first) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + let (_, _, second) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + assert_eq!((new, again), (0, 1), "only pane a's Zoom In reader resolves again"); + assert_eq!(first + second, 1, "the wakes walk only the reader of the published key"); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "publishing the same state again walks nothing"); +} + +/// A change of the gate's props asks the gate once per shown command and resolves again only the readers whose answer +/// changed; a new gate with the same props asks nothing. +#[trial] +fn a_gate_props_change_resolves_only_the_readers_whose_answer_changed() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, SAVE_READERS), "only Save's readers, which the gate now refuses, resolve again"); + assert_eq!(ASKS.with(Cell::get), COMMANDS, "the gate is asked once per shown command"); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, 0), "a gate with the same props resolves nothing"); + assert_eq!(ASKS.with(Cell::get), 0, "and is not asked"); +} + +/// Moving the focus between taps resolves none of them: each finds its command's instance in its own chain, or the +/// command is the app's, so none reads the focus. +#[trial] +fn a_focus_move_resolves_no_reader_that_does_not_read_the_focus() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + for at in [0, 17, 42] { + let id = scene.ids.borrow()[at]; + request(&frames.ctx, FocusTarget::Id(id)); + for _ in 0..2 { + assert_eq!(frame(&mut frames, &scene), (0, 0), "focusing tap {at} resolves nothing"); + } + } +} + +/// An instance that misses exactly one pass and registers again is live again for every kept resolution in the +/// frame it comes back in: its return moves the inputs every resolution reads. +#[trial] +fn an_instance_back_after_one_missed_pass_is_live_again() { + let shown = Cell::new(true); + let enabled = Cell::new(false); + let mut show = |ui: &mut Ui| { + if shown.get() { + Pane::new().id_salt("b").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + } + enabled.set(resolve(ui.ctx(), PaneCommand::ZoomIn).enabled); + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(enabled.get(), "Zoom In reaches the pane"); + shown.set(false); + assert_eq!(frames.frame(vec![], &mut show), 1, "the pane misses one pass"); + shown.set(true); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "the pane is live again in the frame it comes back in"); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "and stays so"); +} + +/// A settled region that shows a command the focused stop answers for (Cut, which a text field takes) runs when that +/// stop's answer changes: with the focus moving from the field to a tap, which takes no edits, Cut no longer waits for a +/// selection. +#[trial] +fn a_settled_region_runs_when_the_focused_stops_answer_changes() { + let text = RefCell::new("hello".to_owned()); + let (field, tap, cut) = (Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)); + let runs = Cell::new(0); + let mut show = |ui: &mut Ui| { + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + tap.set(Tap::new().id_salt("plain").show(ui).id); + Lazy::new("edits", 0.0).settles(true).show(ui, |ui| { + runs.set(runs.get() + 1); + cut.set(Button::command(EditCommands::Cut).show(ui).id); + }); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + request(&frames.ctx, FocusTarget::Id(field.get())); + frames.idle(30, &mut show); + assert!(frames.tree().is_disabled(cut.get()), "Cut does nothing with no text selected"); + runs.set(0); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 0, "the region is settled"); + request(&frames.ctx, FocusTarget::Id(tap.get())); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 1, "the new answer for Cut runs the region once"); + assert!(!frames.tree().is_disabled(cut.get()), "which shows Cut enabled"); +} + +/// The testing check every 100th pass compares every kept resolution with a full one, and every kept gate answer with +/// the gate's. The script changes, a few passes before each check, every kind of input a resolution reads: app and +/// published states, the gate, the keymap, the focus and the focused stop's edits, a menu and a modal layer with readers +/// inside (a palette's reader under the layer), an instance that misses one pass and a scope's parent. +#[trial] +fn the_hundredth_pass_check_finds_every_kept_resolution_current() { + let scene = Scene { global: true, ..Scene::new() }; + let text = RefCell::new("hello".to_owned()); + let (field, opener) = (Cell::new(Id::NULL), Cell::new(Pos2::ZERO)); + let modal = Cell::new(false); + let mut show = |ui: &mut Ui| { + scene.show(ui); + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + Tap::new().id_salt("cut").command(EditCommands::Cut).show(ui); + Dock::new().id_salt("dock").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + let open = Tap::new().id_salt("opener").show(ui); + opener.set(open.rect.center()); + Menu::new("Menu").opened_by(&open, Trigger::Click).show(ui, |ui, _| { + MenuItem::command(AppCommand::Save).show(ui); + MenuItem::command(EditCommands::Cut).show(ui); + }); + let mut open = modal.get(); + Dialog::new("Options").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, cx| { + cx.publish(EditCommands::Undo, CommandState::new()); + resolve_beneath(ui.ctx(), AppCommand::Save); + Tap::new().id_salt("in dialog").command(EditCommands::Undo).show(ui); + }); + modal.set(open); + }; + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + let mut refuses = false; + // A new catalog generation rebuilds the keymap. + let mut generation = 1; + let input = |states: &Tracked, refuses: bool, generation: u64| { + let extra = CommandDef::new(CommandRef::new("trial.extra"), "Extra", Scope::app()) + .with_default(Binding::parse(if generation.is_multiple_of(2) { "F7" } else { "F6" }).expect("the trial's chord parses")); + gated(states, refuses).catalog(AppCatalog::new(vec![extra], generation).expect("the trial's catalog is valid")) + }; + frames.commands(input(&states, refuses, generation)); + // Each step at the pass it names, relative to a check at 100 and 200. + let script: Vec<(usize, &str)> = [100, 200] + .into_iter() + .flat_map(|check| { + let steps: &[(usize, &str)] = if check == 100 { + &[(14, "focus field"), (12, "select all"), (10, "press opener"), (9, "release opener"), (6, "parent"), (3, "skip a"), (1, "state")] + } else { + &[(14, "focus field"), (12, "collapse"), (10, "modal"), (8, "keymap"), (6, "gate"), (3, "skip a"), (1, "publish")] + }; + steps.iter().map(move |(before, step)| (check - before, *step)).collect::>() + }) + .chain([(103, "escape"), (203, "close modal")]) + .collect(); + let mut script = script.into_iter().peekable(); + let (mut passes, mut checked) = (0, Vec::new()); + while passes < 260 { + let mut events = Vec::new(); + if let Some((_, step)) = script.next_if(|(at, _)| passes + 1 >= *at) { + match step { + "focus field" => { + request(&frames.ctx, FocusTarget::Id(field.get())); + } + "select all" => events.push(key_press(Key::A, Modifiers::COMMAND)), + "collapse" => events.push(key_press(Key::ArrowRight, Modifiers::NONE)), + "press opener" => events.push(press(opener.get())), + "release opener" => events.push(release(opener.get())), + "escape" => events.push(key_press(Key::Escape, Modifiers::NONE)), + "skip a" => scene.skip_a.set(true), + "parent" => declare_child(&frames.ctx, DOCK, PANE), + "state" => states.set(AppCommand::Go, CommandState::new().checked(true)), + "gate" => refuses = !refuses, + "keymap" => generation += 1, + "publish" => scene.zoom.set(!scene.zoom.get()), + "modal" => modal.set(true), + _ => modal.set(false), + } + } + frames.commands(input(&states, refuses, generation)); + passes += frames.frame(events, &mut show); + let compared = last_pass_resolves(&frames.ctx, Resolve::Checked); + if compared > 0 { + checked.push(compared); + } + } + assert_eq!(script.next().map(|(_, step)| step), None, "every step ran"); + assert_eq!(checked.len(), 2, "two checks ran: {checked:?}"); + assert!(checked.iter().all(|compared| *compared > KEPT), "each compared the panes' readers and the script's: {checked:?}"); +} diff --git a/crates/ui-widgets/src/bars/items.rs b/crates/ui-widgets/src/bars/items.rs index 471a841f2..97163b91e 100644 --- a/crates/ui-widgets/src/bars/items.rs +++ b/crates/ui-widgets/src/bars/items.rs @@ -108,7 +108,7 @@ pub struct BarItemsStyle { #[derive(Clone)] struct Present { item: BarItem, - resolved: ResolvedCommand, + resolved: std::sync::Arc, } /// Where the parts of a strip sit this pass. diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index 0cfb90755..9c3bdce04 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -343,7 +343,7 @@ impl<'a> Notice<'a> { self.actions .iter() .map(|action| match &action.command { - Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label)), + Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label.clone())), None => action.label.clone(), }) .collect() diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index 697e9edaf..6f11bd7e0 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -161,7 +161,7 @@ impl Component for Table<'_, K> { Divider::horizontal().show(ui); } for (command, enabled) in &commands { - let label = crate::runtime::commands::resolve(&ctx, *command).label; + let label = crate::runtime::commands::resolve(&ctx, *command).label.clone(); if MenuItem::new(label.to_string()).enabled(*enabled).show(ui).ran { picks.push(ColumnRequest::Command(*command)); } diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index 317b8d902..7774f7a8c 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -6,10 +6,10 @@ use crate::values::kit::{AT, INITIAL, Scrub, Seen}; use craft_theme::{Contrast, Mode, Size}; use craft_ui::buttons::Button; use craft_ui::choice::{Radio, RadioGroup}; -use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing, Tracked}; use craft_ui::display::Spinner; use craft_ui::layout_components::Stack; -use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _}; +use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, CommandStates, Commands as _}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; @@ -381,7 +381,11 @@ fn an_app_command_state_runs_the_settled_child_that_shows_it() { let mut frames = Frames::new(); scene.settle(&mut frames); assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled"); - let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled)); + let mut states = Tracked::new(CommandStates::new()); + let mut disable = |enabled: bool| { + states.set(Shown::Visible, CommandState::new().enabled(enabled)); + CommandInput::new().states(&states) + }; frames.commands(disable(false)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Shown runs: {reader}, {beside}"); @@ -425,7 +429,9 @@ fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() { let mut frames = Frames::new(); scene.settle(&mut frames); assert_eq!(scene.frame(&mut frames).1, [0, 0], "the child holding the measured body settles"); - frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false))); + let mut states = Tracked::new(CommandStates::new()); + states.set(Shown::Measured, CommandState::new().enabled(false)); + frames.commands(CommandInput::new().states(&states)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Measured runs: {reader}, {beside}"); assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it"); diff --git a/crates/update/src/install/tests.rs b/crates/update/src/install/tests.rs index 528cca611..a61f9fdd2 100644 --- a/crates/update/src/install/tests.rs +++ b/crates/update/src/install/tests.rs @@ -719,6 +719,22 @@ mod macos_checks { app } + /// Runs `hdiutil` with `args` (the caller holds its [`macos::disk_image_turn`]). The disk-image + /// helper can turn a request away with EAGAIN ("Resource temporarily unavailable") while it + /// is busy elsewhere, as on shared CI runners; that reply alone is retried, up to five + /// attempts over about eight seconds. Any other result returns at once. + fn hdiutil(args: &[&std::ffi::OsStr]) -> std::process::Output { + let mut output = std::process::Command::new("hdiutil").args(args).output().unwrap(); + for wait_ms in [500, 1000, 2000, 4000] { + if output.status.success() || !String::from_utf8_lossy(&output.stderr).contains("Resource temporarily unavailable") { + break; + } + std::thread::sleep(std::time::Duration::from_millis(wait_ms)); + output = std::process::Command::new("hdiutil").args(args).output().unwrap(); + } + output + } + /// A release-style disk image holding a `PhotoCraft.app` that reports `version`. The tests, /// in this process and in others, ask the disk-image helper one at a time; when a program /// that is not one of these tests keeps it busy, the test fails with what `hdiutil create` @@ -728,12 +744,17 @@ mod macos_checks { bundle(&src, version); let dmg = dir.join(format!("photocraft-{version}-macos-universal.dmg")); let _one_at_a_time = macos::disk_image_turn(); - let output = std::process::Command::new("hdiutil") - .args(["create", "-quiet", "-format", "UDZO", "-volname", "PhotoCraft", "-srcfolder"]) - .arg(&src) - .arg(&dmg) - .output() - .unwrap(); + let output = hdiutil(&[ + "create".as_ref(), + "-quiet".as_ref(), + "-format".as_ref(), + "UDZO".as_ref(), + "-volname".as_ref(), + "PhotoCraft".as_ref(), + "-srcfolder".as_ref(), + src.as_os_str(), + dmg.as_os_str(), + ]); assert!(output.status.success(), "hdiutil create failed: {}", String::from_utf8_lossy(&output.stderr).trim()); dmg } @@ -916,12 +937,16 @@ mod macos_checks { // One request at a time, as in `dmg`. let output = { let _one_at_a_time = macos::disk_image_turn(); - std::process::Command::new("hdiutil") - .args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-noverify", "-mountpoint"]) - .arg(&mount) - .arg(&image) - .output() - .unwrap() + hdiutil(&[ + "attach".as_ref(), + "-nobrowse".as_ref(), + "-readonly".as_ref(), + "-noautoopen".as_ref(), + "-noverify".as_ref(), + "-mountpoint".as_ref(), + mount.as_os_str(), + image.as_os_str(), + ]) }; let _attached = Attached(mount.clone()); assert!(output.status.success(), "hdiutil attach failed: {}", String::from_utf8_lossy(&output.stderr).trim()); diff --git a/crates/usd/Cargo.toml b/crates/usd/Cargo.toml index ac1c64d0c..a97954d7f 100644 --- a/crates/usd/Cargo.toml +++ b/crates/usd/Cargo.toml @@ -11,5 +11,6 @@ repository.workspace = true workspace = true [dependencies] +half = "2" lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } thiserror.workspace = true diff --git a/crates/usd/README.md b/crates/usd/README.md index fcf585760..47f624c47 100644 --- a/crates/usd/README.md +++ b/crates/usd/README.md @@ -1,7 +1,11 @@ # craft-usd -Bounded wire primitives for USD Crate, independent of application scene and material models. +Bounded wire primitives and neutral `.usda`/`.usdc` scene, prim, and layer read/write for USD, independent of application mesh and material models. -Provides bounded integer-delta array decoding and Crate-framed LZ4 compression/decompression: a single unprefixed block or up to 127 length-prefixed blocks, under a caller-provided output-byte cap with fallible output allocation. Trailing bytes after counted chunks retain the original reader's ignored-tail policy. This is not a complete USD reader/writer; scene interpretation, integer packing and full scene export remain outside this extraction. Compression uses a caller cap on worst-case reserved output and fallible allocation. Integer decoding uses explicit 32/64-bit widths, signed wrapping arithmetic, a caller output-byte cap and fallible allocation. +Provides: +- Bounded integer-delta array decoding/encoding and Crate-framed LZ4 compression/decompression (`compress`, `integers`, `decompress`) under caller-provided output-byte caps with fallible allocation. +- Shared Crate wire constants and type metadata (`codec`). +- Neutral `.usda` (text) and `.usdc` (Crate binary) layer reader (`scene::read_layer`, `scene::read_layer_with_budget`) preserving `def`/`over`/`class` specifiers, internal references, coordinate metadata (`metersPerUnit`, `upAxis`), payload/sublayer/variant warnings, and decoded byte budgets (`scene::Budget`). +- Neutral `.usda` and `.usdc` scene/prim/layer writer (`scene::write_usda`, `scene::write_usdc`). -Adapted from TextureCraft `crates/formats/src/mesh_import/usd/codec.rs`, introduced by bflatastic in `bdbb52c9b66b221a55b370105b42f485a76e6fc7`. The LZ4 backend is MIT-licensed `lz4_flex`. +Adapted from TextureCraft's `mesh_import/usd` and `mesh_export/{usd,usdc}.rs`, originally introduced by bflatastic in `bdbb52c9b66b221a55b370105b42f485a76e6fc7`. The LZ4 backend is MIT-licensed `lz4_flex`. diff --git a/crates/usd/src/codec.rs b/crates/usd/src/codec.rs new file mode 100644 index 000000000..659cc87f1 --- /dev/null +++ b/crates/usd/src/codec.rs @@ -0,0 +1,113 @@ +//! Shared USD Crate (`.usdc`) wire constants and type metadata. + +/// Magic bytes at the start of every USD Crate file. +pub const MAGIC: &[u8; 8] = b"PXR-USDC"; +/// Size of the bootstrap header: magic, version, TOC offset, reserved. +pub const BOOTSTRAP_LEN: usize = 88; +/// Arrays shorter than this are never stored compressed. +pub const MIN_COMPRESSED_ARRAY: usize = 16; + +/// ValueRep array flag. +pub const IS_ARRAY: u64 = 1 << 63; +/// ValueRep inline flag. +pub const IS_INLINED: u64 = 1 << 62; +/// ValueRep compressed flag. +pub const IS_COMPRESSED: u64 = 1 << 61; +/// ValueRep array-edit flag. +pub const IS_ARRAY_EDIT: u64 = 1 << 60; +/// ValueRep 48-bit payload mask. +pub const PAYLOAD_MASK: u64 = (1 << 48) - 1; + +/// Value type ids (Crate data types). +pub mod ty { + pub const BOOL: u8 = 1; + pub const UCHAR: u8 = 2; + pub const INT: u8 = 3; + pub const UINT: u8 = 4; + pub const INT64: u8 = 5; + pub const UINT64: u8 = 6; + pub const HALF: u8 = 7; + pub const FLOAT: u8 = 8; + pub const DOUBLE: u8 = 9; + pub const STRING: u8 = 10; + pub const TOKEN: u8 = 11; + pub const ASSET_PATH: u8 = 12; + pub const MATRIX2D: u8 = 13; + pub const MATRIX3D: u8 = 14; + pub const MATRIX4D: u8 = 15; + pub const QUATD: u8 = 16; + pub const QUATF: u8 = 17; + pub const QUATH: u8 = 18; + pub const VEC2D: u8 = 19; + pub const VEC2F: u8 = 20; + pub const VEC3F: u8 = 24; + pub const VEC4F: u8 = 28; + pub const VEC4I: u8 = 30; + pub const TOKEN_LIST_OP: u8 = 32; + pub const PATH_LIST_OP: u8 = 34; + pub const REFERENCE_LIST_OP: u8 = 35; + pub const PATH_VECTOR: u8 = 40; + pub const TOKEN_VECTOR: u8 = 41; + pub const SPECIFIER: u8 = 42; + pub const PERMISSION: u8 = 43; + pub const VARIABILITY: u8 = 44; + pub const TIME_SAMPLES: u8 = 46; + pub const DOUBLE_VECTOR: u8 = 48; +} + +/// Scalar kind of numeric Crate types. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Scalar { + U8, + I32, + U32, + I64, + U64, + F16, + F32, + F64, +} + +impl Scalar { + /// Byte size of one scalar element. + pub fn size(self) -> usize { + match self { + Self::U8 => 1, + Self::F16 => 2, + Self::I32 | Self::U32 | Self::F32 => 4, + Self::I64 | Self::U64 | Self::F64 => 8, + } + } +} + +/// `(scalar, components)` of numeric type `t`, or `None` for non-numeric types. +pub fn numeric(t: u8) -> Option<(Scalar, usize)> { + Some(match t { + ty::BOOL | ty::UCHAR => (Scalar::U8, 1), + ty::INT => (Scalar::I32, 1), + ty::UINT => (Scalar::U32, 1), + ty::INT64 => (Scalar::I64, 1), + ty::UINT64 => (Scalar::U64, 1), + ty::HALF => (Scalar::F16, 1), + ty::FLOAT => (Scalar::F32, 1), + ty::DOUBLE => (Scalar::F64, 1), + ty::MATRIX2D => (Scalar::F64, 4), + ty::MATRIX3D => (Scalar::F64, 9), + ty::MATRIX4D => (Scalar::F64, 16), + ty::QUATD => (Scalar::F64, 4), + ty::QUATF => (Scalar::F32, 4), + ty::QUATH => (Scalar::F16, 4), + // Vec{2,3,4}{d,f,h,i}: ids 19..=30 in that order. + ty::VEC2D..=ty::VEC4I => { + let k = t - ty::VEC2D; + let scalar = [Scalar::F64, Scalar::F32, Scalar::F16, Scalar::I32][usize::from(k % 4)]; + (scalar, usize::from(k / 4) + 2) + } + _ => return None, + }) +} + +/// Upper bound of the encoded size of `n` integers of `width` bytes. +pub fn encoded_ints_len(n: usize, width: usize) -> usize { + if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) } +} diff --git a/crates/usd/src/lib.rs b/crates/usd/src/lib.rs index 33c7f3484..9bf2a88a2 100644 --- a/crates/usd/src/lib.rs +++ b/crates/usd/src/lib.rs @@ -1,16 +1,22 @@ -//! Bounded USD Crate wire primitives. Not a complete USD scene reader or writer. +//! Bounded USD Crate wire primitives and neutral `.usda`/`.usdc` scene/prim/layer read/write. //! -//! The framing decoder is adapted from TextureCraft's `usd/codec.rs`, originally +//! The Crate framing decoder is adapted from TextureCraft's `usd/codec.rs`, originally //! bflatastic, commit bdbb52c9b66b221a55b370105b42f485a76e6fc7. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Shared USD Crate wire constants and type metadata. +pub mod codec; + /// Bounded single-block Crate LZ4 compression. pub mod compress; /// Bounded Crate integer delta arrays. pub mod integers; +/// Neutral USDA/USDC scene, prim, and layer read/write. +pub mod scene; + /// Failure to read a bounded Crate LZ4 frame. #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/crates/usd/src/scene/mod.rs b/crates/usd/src/scene/mod.rs new file mode 100644 index 000000000..25fbbe0cb --- /dev/null +++ b/crates/usd/src/scene/mod.rs @@ -0,0 +1,275 @@ +//! Neutral USDA/USDC scene, prim, and layer read/write. +//! +//! Parses `.usda` (text) and `.usdc` (Crate binary) layers into a neutral [`Layer`](crate::scene::Layer) +//! representation (keeping `def`/`over`/`class` specifiers, internal references, coordinate +//! metadata, payload/sublayer/variant warnings, and decoded byte budgets), and writes neutral +//! [`UsdLayer`](crate::scene::UsdLayer) scenes to `.usda` text or `.usdc` Crate binary. + +pub mod usda; +pub mod usdc; +pub mod write; + +use std::collections::HashMap; + +use crate::codec; + +/// Default memory budget for decoded layer values (2 GiB). +pub const MAX_DECODED_BYTES: usize = 1 << 31; +/// Deepest prim nesting and reference chain followed. +pub const MAX_DEPTH: usize = 128; + +/// Error returned when reading or writing a USD layer or scene. +#[derive(Debug, thiserror::Error)] +pub enum SceneError { + /// Syntax, framing, or structural error in the input. + #[error("malformed USD: {0}")] + Malformed(String), + /// Decoded data or table size exceeds the configured budget or limit. + #[error("{0}")] + TooLarge(String), + /// Unsupported USD Crate version. + #[error("unsupported USD: {0}")] + Unsupported(String), + /// Invalid scene structure when writing (for example, an unknown target path). + #[error("invalid USD: {0}")] + Invalid(String), +} + +/// Result alias for USD scene operations. +pub type Result = std::result::Result; + +/// Charges decoded data against a byte ceiling. +#[derive(Clone, Debug)] +pub struct Budget(pub usize); + +impl Budget { + /// Create a budget with [`MAX_DECODED_BYTES`]. + pub fn new() -> Self { + Self(MAX_DECODED_BYTES) + } + + /// Create a budget with a custom byte limit. + pub fn with_limit(limit: usize) -> Self { + Self(limit) + } + + /// Deduct `bytes` from the remaining budget, failing with [`SceneError::TooLarge`] if exceeded. + pub fn take(&mut self, bytes: usize) -> Result<()> { + self.0 = self + .0 + .checked_sub(bytes) + .ok_or_else(|| SceneError::TooLarge(format!("the USD file decodes to more than {} MiB", MAX_DECODED_BYTES >> 20)))?; + Ok(()) + } +} + +impl Default for Budget { + fn default() -> Self { + Self::new() + } +} + +/// A decoded value: numbers (scalars, vectors, quaternions as `w x y z`, matrices row-major, +/// and bools all flattened), tokens / strings / asset paths, or prim/property paths. +#[derive(Clone, Debug, PartialEq)] +pub enum Val { + Num(Vec), + Tok(Vec), + Path(Vec), +} + +/// A decoded prim property (attribute or relationship). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Prop { + /// Declared type (`point3f[]`, `texCoord2f[]`, `rel`, ...). + pub type_name: String, + pub value: Option, + pub interpolation: Option, + /// The first connection source (`name.connect`): an attribute path. + pub connect: Option, +} + +/// Prim specifier (`def`, `over`, `class`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Specifier { + #[default] + Def, + Over, + Class, +} + +/// One prim spec of a decoded [`Layer`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PrimSpec { + pub name: String, + pub path: String, + pub type_name: String, + pub specifier: Specifier, + pub active: Option, + pub props: HashMap, + pub children: Vec, + /// Internal references: absolute prim paths in this layer. + pub references: Vec, +} + +/// A parsed USD layer: prim specs (index 0 is the pseudo-root `/`) and stage metadata. +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub prims: Vec, + pub meters_per_unit: Option, + pub up_axis: Option, + pub warnings: Vec, +} + +impl Layer { + /// Create an empty layer with a pseudo-root prim at index 0 (`"/"`). + pub fn new() -> Self { + Self { prims: vec![PrimSpec { path: "/".into(), ..PrimSpec::default() }], meters_per_unit: None, up_axis: None, warnings: Vec::new() } + } + + /// Add a prim spec named `name` under prim `parent` and return its index. + pub fn add_prim(&mut self, parent: usize, name: &str) -> usize { + let path = match self.prims.get(parent) { + Some(p) if p.path == "/" => format!("/{name}"), + Some(p) => format!("{}/{name}", p.path), + None => format!("/{name}"), + }; + let id = self.prims.len(); + self.prims.push(PrimSpec { name: name.into(), path, ..PrimSpec::default() }); + if let Some(p) = self.prims.get_mut(parent) { + p.children.push(id); + } + id + } + + /// Record a deduplicated warning message on the layer. + pub fn warn(&mut self, msg: &str) { + if !self.warnings.iter().any(|w| w == msg) { + self.warnings.push(msg.into()); + } + } +} + +impl Default for Layer { + fn default() -> Self { + Self::new() + } +} + +/// Read a `.usda` or `.usdc` layer from `bytes` using [`Budget::new()`]. +pub fn read_layer(bytes: &[u8]) -> Result { + let mut budget = Budget::new(); + read_layer_with_budget(bytes, &mut budget) +} + +/// Read a `.usda` or `.usdc` layer from `bytes`, charging decoded allocations to `budget`. +pub fn read_layer_with_budget(bytes: &[u8], budget: &mut Budget) -> Result { + if bytes.starts_with(codec::MAGIC) { + usdc::read(bytes, budget) + } else if bytes.trim_ascii_start().starts_with(b"#usda") { + usda::read(bytes, budget) + } else { + Err(SceneError::Malformed("neither a USD text layer (#usda) nor a Crate binary (PXR-USDC)".into())) + } +} + +/// A value written to a [`UsdLayer`]. +#[derive(Clone, Debug, PartialEq)] +pub enum UsdValue { + Token(String), + Str(String), + Int(i32), + Double(f64), + Asset(String), + Float4([f32; 4]), + Ints(Vec), + Vec2fs(Vec<[f32; 2]>), + Vec3fs(Vec<[f32; 3]>), + /// A relationship target or attribute connection (absolute path). + Target(String), +} + +/// An attribute (or, with type `"rel"`, a relationship) to write. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdAttr { + pub name: String, + pub type_name: String, + pub uniform: bool, + pub value: Option, + /// Connection source of an attribute (`name.connect`). + pub connect: Option, + pub interpolation: Option, +} + +impl UsdAttr { + /// Create a new attribute with `name`, `type_name`, and optional `value`. + pub fn new(name: &str, type_name: &str, value: Option) -> Self { + Self { name: name.into(), type_name: type_name.into(), uniform: false, value, connect: None, interpolation: None } + } + + /// Mark this attribute as `uniform`. + pub fn uniform(mut self) -> Self { + self.uniform = true; + self + } + + /// Set the `interpolation` metadata on this attribute. + pub fn with_interpolation(mut self, interpolation: &str) -> Self { + self.interpolation = Some(interpolation.into()); + self + } + + /// Create a relationship (`rel`) targeting `target`. + pub fn rel(name: &str, target: String) -> Self { + Self::new(name, "rel", Some(UsdValue::Target(target))) + } + + /// Create a connected attribute (`name.connect = `). + pub fn connected(name: &str, type_name: &str, source: String) -> Self { + Self { connect: Some(source), ..Self::new(name, type_name, None) } + } +} + +/// A prim to write into a [`UsdLayer`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdPrim { + pub name: String, + pub type_name: String, + /// Applies `MaterialBindingAPI` (when the prim has a `material:binding`). + pub binding_api: bool, + pub attrs: Vec, + pub children: Vec, +} + +impl UsdPrim { + /// Create a new `def` prim with `name` and `type_name`. + pub fn new(name: &str, type_name: &str) -> Self { + Self { name: name.into(), type_name: type_name.into(), binding_api: false, attrs: Vec::new(), children: Vec::new() } + } +} + +/// A neutral writable USD layer with its root prim and stage metadata. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdLayer { + pub root: UsdPrim, + pub doc: Option, + pub meters_per_unit: f64, + pub up_axis: String, +} + +impl UsdLayer { + /// Create a writable layer with `root` as the default prim, `metersPerUnit = 1`, `upAxis = "Y"`. + pub fn new(root: UsdPrim) -> Self { + Self { root, doc: None, meters_per_unit: 1.0, up_axis: "Y".into() } + } +} + +/// Format `layer` as `.usda` text. +pub fn write_usda(layer: &UsdLayer) -> String { + write::usda(layer) +} + +/// Encode `layer` as a `.usdc` Crate binary. +pub fn write_usdc(layer: &UsdLayer) -> Result> { + write::usdc(layer) +} diff --git a/crates/usd/src/scene/usda.rs b/crates/usd/src/scene/usda.rs new file mode 100644 index 000000000..40637ea04 --- /dev/null +++ b/crates/usd/src/scene/usda.rs @@ -0,0 +1,512 @@ +//! The USD text format (`.usda`): layer metadata, `def` / `over` / `class` prims with metadata +//! (`references`, `active`), attributes (default values, the first time sample, +//! `interpolation`) and relationships. Variant sets, dictionaries and connections are skipped. + +use super::{Budget, Layer, Result, SceneError, Specifier, Val}; + +/// Deepest value / prim nesting accepted. +const MAX_NESTING: usize = 128; + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Punct(u8), + Ident(String), + Str(String), + Num(f64), + Asset(String), + Path(String), + Eof, +} + +struct Lexer<'a> { + s: &'a [u8], + pos: usize, + peeked: Option, +} + +fn is_ident_start(c: u8) -> bool { + c.is_ascii_alphabetic() || c == b'_' +} + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || matches!(c, b'_' | b':' | b'.') +} + +impl Lexer<'_> { + fn at(&self, k: usize) -> u8 { + self.s.get(self.pos + k).copied().unwrap_or(0) + } + + fn line(&self) -> usize { + 1 + self.s.get(..self.pos).unwrap_or_default().iter().filter(|&&c| c == b'\n').count() + } + + fn err(&self, msg: impl std::fmt::Display) -> SceneError { + SceneError::Malformed(format!("line {}: {msg}", self.line())) + } + + fn skip_space(&mut self) { + loop { + match self.at(0) { + b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1, + b'#' => self.skip_until(b"\n"), + b'/' if self.at(1) == b'/' => self.skip_until(b"\n"), + b'/' if self.at(1) == b'*' => { + self.pos += 2; + self.skip_until(b"*/"); + self.pos = (self.pos + 2).min(self.s.len()); + } + _ => return, + } + } + } + + /// Advance to the next `end` (or the end of input). + fn skip_until(&mut self, end: &[u8]) { + let rest = self.s.get(self.pos..).unwrap_or_default(); + self.pos += rest.windows(end.len()).position(|w| w == end).unwrap_or(rest.len()); + } + + /// Bytes up to the next `end`, consuming the delimiter. + fn delimited(&mut self, end: &[u8]) -> Result<&[u8]> { + let start = self.pos; + self.skip_until(end); + if self.pos >= self.s.len() { + return Err(self.err("unterminated string, asset path or path")); + } + let body = self.s.get(start..self.pos).unwrap_or_default(); + self.pos += end.len(); + Ok(body) + } + + fn string(&mut self, quote: u8) -> Result { + if self.at(0) == quote && self.at(1) == quote { + self.pos += 2; + let body = self.delimited(&[quote; 3])?; + return Ok(String::from_utf8_lossy(body).into_owned()); + } + let mut out = Vec::new(); + loop { + match self.at(0) { + 0 if self.pos >= self.s.len() => return Err(self.err("unterminated string")), + b'\n' => return Err(self.err("newline in a string")), + b'\\' => { + out.push(match self.at(1) { + b'n' => b'\n', + b't' => b'\t', + c => c, + }); + self.pos += 2; + } + c if c == quote => { + self.pos += 1; + return Ok(String::from_utf8_lossy(&out).into_owned()); + } + c => { + out.push(c); + self.pos += 1; + } + } + } + } + + fn lex(&mut self) -> Result { + self.skip_space(); + let c = self.at(0); + if self.pos >= self.s.len() { + return Ok(Tok::Eof); + } + let text = |s: &[u8]| String::from_utf8_lossy(s).into_owned(); + Ok(match c { + b'"' | b'\'' => { + self.pos += 1; + Tok::Str(self.string(c)?) + } + b'@' if self.at(1) == b'@' && self.at(2) == b'@' => { + self.pos += 3; + Tok::Asset(text(self.delimited(b"@@@")?)) + } + b'@' => { + self.pos += 1; + Tok::Asset(text(self.delimited(b"@")?)) + } + b'<' => { + self.pos += 1; + Tok::Path(text(self.delimited(b">")?)) + } + b'0'..=b'9' | b'-' | b'+' | b'.' => { + let start = self.pos; + self.pos += 1; + while self.at(0).is_ascii_alphanumeric() || matches!(self.at(0), b'.' | b'-' | b'+') { + self.pos += 1; + } + let word = std::str::from_utf8(self.s.get(start..self.pos).unwrap_or_default()).unwrap_or_default(); + Tok::Num(word.parse().map_err(|_| self.err(format!("bad number \"{word}\"")))?) + } + c if is_ident_start(c) => { + let start = self.pos; + while is_ident(self.at(0)) { + self.pos += 1; + } + Tok::Ident(text(self.s.get(start..self.pos).unwrap_or_default())) + } + c => { + self.pos += 1; + Tok::Punct(c) + } + }) + } + + fn next(&mut self) -> Result { + match self.peeked.take() { + Some(t) => Ok(t), + None => self.lex(), + } + } + + fn peek(&mut self) -> Result<&Tok> { + if self.peeked.is_none() { + self.peeked = Some(self.lex()?); + } + Ok(self.peeked.get_or_insert(Tok::Eof)) + } + + fn eat(&mut self, p: u8) -> Result { + let hit = *self.peek()? == Tok::Punct(p); + if hit { + self.peeked = None; + } + Ok(hit) + } + + fn expect(&mut self, p: u8) -> Result<()> { + match self.next()? { + Tok::Punct(c) if c == p => Ok(()), + t => Err(self.err(format!("expected '{}', found {t:?}", p as char))), + } + } +} + +/// A value, flattened: numbers, strings (tokens, asset paths) and paths in document order. +#[derive(Default)] +struct Acc { + nums: Vec, + strs: Vec, + paths: Vec, + /// The last item was an asset path (a path right after one names a prim in that asset). + after_asset: bool, + none: bool, +} + +impl Acc { + fn into_val(self) -> Option { + if self.none { + None + } else if !self.paths.is_empty() { + Some(Val::Path(self.paths)) + } else if !self.strs.is_empty() { + Some(Val::Tok(self.strs)) + } else { + Some(Val::Num(self.nums)) + } + } +} + +struct Parser<'a, 'b> { + lx: Lexer<'a>, + layer: Layer, + budget: &'b mut Budget, +} + +/// Metadata keys whose values are kept. +const KEPT_METADATA: [&str; 7] = ["metersPerUnit", "upAxis", "subLayers", "references", "active", "interpolation", "payload"]; + +/// Parse a `.usda` text layer, charging decoded allocations against `budget`. +pub fn read(bytes: &[u8], budget: &mut Budget) -> Result { + let mut lx = Lexer { s: bytes, pos: 0, peeked: None }; + // The header is a comment: `#usda 1.0`. + lx.skip_space(); + let mut p = Parser { lx, layer: Layer::new(), budget }; + if *p.lx.peek()? == Tok::Punct(b'(') { + for (key, acc) in p.metadata()? { + match (key.as_str(), acc.into_val()) { + ("metersPerUnit", Some(Val::Num(v))) => p.layer.meters_per_unit = v.first().copied(), + ("upAxis", Some(Val::Tok(v))) => p.layer.up_axis = v.into_iter().next(), + ("subLayers", Some(Val::Tok(v))) if !v.is_empty() => p.layer.warn("sublayers are not loaded"), + _ => {} + } + } + } + loop { + match p.lx.next()? { + Tok::Eof => break, + Tok::Ident(kw) if matches!(kw.as_str(), "def" | "over" | "class") => p.prim(0, &kw, 0)?, + Tok::Punct(b';') => {} + t => return Err(p.lx.err(format!("expected a prim, found {t:?}"))), + } + } + Ok(p.layer) +} + +impl Parser<'_, '_> { + /// One value into `acc`. + fn value(&mut self, acc: &mut Acc, depth: usize) -> Result<()> { + if depth > MAX_NESTING { + return Err(self.lx.err("values are nested too deeply")); + } + let after_asset = std::mem::take(&mut acc.after_asset); + match self.lx.next()? { + Tok::Num(v) => { + self.budget.take(8)?; + acc.nums.push(v); + } + Tok::Ident(w) => match w.as_str() { + "true" | "false" => { + self.budget.take(8)?; + acc.nums.push(if w == "true" { 1.0 } else { 0.0 }); + } + "inf" | "nan" => { + self.budget.take(8)?; + acc.nums.push(w.parse().unwrap_or(f64::NAN)); + } + "None" => acc.none = true, + _ => self.push_str(acc, w)?, + }, + Tok::Str(s) => self.push_str(acc, s)?, + Tok::Asset(s) => { + self.push_str(acc, s)?; + acc.after_asset = true; + } + // A path right after an asset path names a prim in that (external) layer. + Tok::Path(_) if after_asset => {} + Tok::Path(p) => { + self.budget.take(p.len() + 24)?; + acc.paths.push(p); + } + Tok::Punct(open @ (b'[' | b'(')) => { + let close = if open == b'[' { b']' } else { b')' }; + loop { + match self.lx.peek()? { + Tok::Punct(c) if *c == close => break, + Tok::Punct(b',' | b';' | b'=') => { + acc.after_asset = false; + self.lx.next()?; + } + Tok::Eof => return Err(self.lx.err("unterminated list")), + _ => self.value(acc, depth + 1)?, + } + } + self.lx.next()?; + } + Tok::Punct(b'{') => self.skip_block(b'{', b'}')?, + t => return Err(self.lx.err(format!("unexpected {t:?} in a value"))), + } + Ok(()) + } + + fn push_str(&mut self, acc: &mut Acc, s: String) -> Result<()> { + self.budget.take(s.len() + 24)?; + acc.strs.push(s); + Ok(()) + } + + /// Skip a balanced block whose opening token was just read. + fn skip_block(&mut self, open: u8, close: u8) -> Result<()> { + let mut depth = 1usize; + while depth > 0 { + match self.lx.next()? { + Tok::Punct(c) if c == open => depth += 1, + Tok::Punct(c) if c == close => depth -= 1, + Tok::Eof => return Err(self.lx.err("unterminated block")), + _ => {} + } + } + Ok(()) + } + + /// A `( ... )` metadata block (the `(` not yet read): the kept entries, by key. List-op + /// `delete` and `reorder` entries are dropped. + fn metadata(&mut self) -> Result> { + self.lx.expect(b'(')?; + let mut out = Vec::new(); + loop { + let (mut key, mut keep) = match self.lx.next()? { + Tok::Punct(b')') => return Ok(out), + Tok::Punct(b';' | b',') | Tok::Str(_) => continue, + Tok::Ident(k) => (k, true), + t => return Err(self.lx.err(format!("unexpected {t:?} in metadata"))), + }; + if matches!(key.as_str(), "prepend" | "append" | "add" | "delete" | "reorder") { + keep = !matches!(key.as_str(), "delete" | "reorder"); + key = match self.lx.next()? { + Tok::Ident(k) => k, + t => return Err(self.lx.err(format!("expected a metadata key, found {t:?}"))), + }; + } + if !self.lx.eat(b'=')? { + continue; + } + let mut acc = Acc::default(); + self.value(&mut acc, 0)?; + if keep && KEPT_METADATA.contains(&key.as_str()) { + out.push((key, acc)); + } + } + } + + fn prim(&mut self, parent: usize, specifier: &str, depth: usize) -> Result<()> { + if depth > MAX_NESTING { + return Err(self.lx.err("prims are nested too deeply")); + } + let (type_name, name) = match self.lx.next()? { + Tok::Ident(t) => match self.lx.next()? { + Tok::Str(n) => (t, n), + t => return Err(self.lx.err(format!("expected a prim name, found {t:?}"))), + }, + Tok::Str(n) => (String::new(), n), + t => return Err(self.lx.err(format!("expected a prim name, found {t:?}"))), + }; + self.budget.take(name.len() * 2 + 256)?; + let id = self.layer.add_prim(parent, &name); + let mut references = Vec::new(); + let mut active = None; + if *self.lx.peek()? == Tok::Punct(b'(') { + for (key, acc) in self.metadata()? { + match key.as_str() { + "references" | "payload" => { + if !acc.strs.is_empty() { + self.layer.warn("external references and payloads are not loaded"); + } + references.extend(acc.paths); + } + "active" => active = acc.nums.first().map(|v| *v != 0.0), + _ => {} + } + } + } + if let Some(spec) = self.layer.prims.get_mut(id) { + spec.type_name = type_name; + spec.specifier = match specifier { + "over" => Specifier::Over, + "class" => Specifier::Class, + _ => Specifier::Def, + }; + spec.active = active; + spec.references = references; + } + self.lx.expect(b'{')?; + loop { + let word = match self.lx.next()? { + Tok::Punct(b'}') => return Ok(()), + Tok::Punct(b';') => continue, + Tok::Ident(w) => w, + t => return Err(self.lx.err(format!("unexpected {t:?} in prim \"{name}\""))), + }; + match word.as_str() { + "def" | "over" | "class" => self.prim(id, &word, depth + 1)?, + "variantSet" => { + self.layer.warn("variant sets are not applied"); + while !self.lx.eat(b'{')? { + if self.lx.next()? == Tok::Eof { + return Err(self.lx.err("unterminated variant set")); + } + } + self.skip_block(b'{', b'}')?; + } + "reorder" => { + self.lx.next()?; + self.lx.expect(b'=')?; + self.value(&mut Acc::default(), 0)?; + } + _ => self.property(id, word)?, + } + } + } + + /// An attribute or relationship whose first word was read. + fn property(&mut self, prim: usize, mut word: String) -> Result<()> { + let mut keep = true; + while matches!(word.as_str(), "custom" | "uniform" | "varying" | "config" | "prepend" | "append" | "add" | "delete") { + keep &= word != "delete"; + word = match self.lx.next()? { + Tok::Ident(w) => w, + t => return Err(self.lx.err(format!("expected a property type, found {t:?}"))), + }; + } + let mut type_name = word; + if self.lx.eat(b'[')? { + self.lx.expect(b']')?; + type_name.push_str("[]"); + } + let full = match self.lx.next()? { + Tok::Ident(n) => n, + t => return Err(self.lx.err(format!("expected a property name, found {t:?}"))), + }; + let (name, suffix) = match full.rsplit_once('.') { + Some((n, s @ ("connect" | "timeSamples" | "spline" | "default"))) => (n.to_string(), s), + _ => (full, ""), + }; + let mut acc = Acc::default(); + let mut has_value = false; + if self.lx.eat(b'=')? { + has_value = true; + if suffix == "timeSamples" || suffix == "spline" { + self.first_sample(&mut acc)?; + } else { + self.value(&mut acc, 0)?; + } + } + let mut interpolation = None; + if *self.lx.peek()? == Tok::Punct(b'(') { + for (key, meta) in self.metadata()? { + if key == "interpolation" { + interpolation = meta.strs.into_iter().next(); + } + } + } + if !keep || suffix == "spline" { + return Ok(()); + } + let Some(spec) = self.layer.prims.get_mut(prim) else { return Ok(()) }; + let prop = spec.props.entry(name).or_default(); + if suffix == "connect" { + prop.connect = acc.paths.into_iter().next(); + return Ok(()); + } + // A plain default and its time samples may both be authored; the default wins. + if has_value && (suffix != "timeSamples" || prop.value.is_none()) { + prop.value = acc.into_val(); + } + prop.type_name = type_name; + if interpolation.is_some() { + prop.interpolation = interpolation; + } + Ok(()) + } + + /// `{ time: value, ... }`: the first sample's value into `acc`, the rest skipped. + fn first_sample(&mut self, acc: &mut Acc) -> Result<()> { + self.lx.expect(b'{')?; + let mut first = true; + loop { + match self.lx.next()? { + Tok::Punct(b'}') => return Ok(()), + Tok::Punct(b',') => {} + Tok::Num(_) => { + self.lx.expect(b':')?; + if first { + self.value(acc, 0)?; + first = acc.none; + acc.none = false; + } else { + let mut skip = Acc::default(); + self.value(&mut skip, 0)?; + // Skipped samples do not stay in memory. + self.budget.0 = self.budget.0.saturating_add(8 * skip.nums.len()); + } + } + t => return Err(self.lx.err(format!("unexpected {t:?} in time samples"))), + } + } + } +} diff --git a/crates/usd/src/scene/usdc.rs b/crates/usd/src/scene/usdc.rs new file mode 100644 index 000000000..89a2daddf --- /dev/null +++ b/crates/usd/src/scene/usdc.rs @@ -0,0 +1,840 @@ +//! The USD Crate binary format (`.usdc`, versions 0.4.0 and newer): bootstrap header, table of +//! contents, the TOKENS / STRINGS / FIELDS / FIELDSETS / PATHS / SPECS sections, and decoded +//! values (numeric scalars, vectors, quaternions, matrices, arrays, tokens, strings, asset paths, +//! token/path vectors, token/path/reference list ops, and the first time sample). + +use std::collections::HashMap; + +use crate::codec::{self, Scalar, ty}; +use crate::integers::{self, Width}; +use crate::scene::{Budget, Layer, MAX_DECODED_BYTES, MAX_DEPTH, Prop, Result, SceneError, Specifier, Val}; + +/// Oldest Crate version read (compressed structural sections). +const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); +const MAX_SECTIONS: usize = 64; +/// Items in one table or array. +const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; + +/// Spec types. +const SPEC_ATTRIBUTE: i64 = 1; +const SPEC_PRIM: i64 = 6; +const SPEC_PSEUDO_ROOT: i64 = 7; +const SPEC_RELATIONSHIP: i64 = 8; +const SPEC_VARIANT: i64 = 10; +const SPEC_VARIANT_SET: i64 = 11; + +fn truncated() -> SceneError { + SceneError::Malformed("the file is truncated or an offset points outside it".into()) +} + +fn check_count(n: u64, cap: usize) -> Result { + usize::try_from(n).ok().filter(|n| *n <= cap).ok_or_else(|| SceneError::TooLarge(format!("USD array of {n} items (limit {cap})"))) +} + +fn decompress_block(input: &[u8], max_out: usize) -> Result> { + crate::decompress(input, max_out).map_err(|e| SceneError::Malformed(e.to_string())) +} + +fn decode_ints(data: &[u8], n: usize, width: usize) -> Result> { + let width = match width { + 4 => Width::I32, + 8 => Width::I64, + _ => return Err(SceneError::Malformed("unsupported integer width".into())), + }; + integers::decode(data, n, width, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +/// A bounds-checked little-endian cursor. +#[derive(Clone)] +struct Cur<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cur<'a> { + fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + let s = self.b.get(self.pos..self.pos.checked_add(n).ok_or_else(truncated)?).ok_or_else(truncated)?; + self.pos += n; + Ok(s) + } + + fn array(&mut self) -> Result<[u8; N]> { + self.bytes(N)?.try_into().map_err(|_| truncated()) + } + + fn u8(&mut self) -> Result { + let [b] = self.array::<1>()?; + Ok(b) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.array()?)) + } + + fn f64(&mut self) -> Result { + Ok(f64::from_le_bytes(self.array()?)) + } + + fn remaining(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + /// A count of items of `item_bytes` each that must fit in the rest of the data (0: items + /// that follow compressed, bounded by [`MAX_ITEMS`] only). + fn count(&mut self, item_bytes: usize) -> Result { + let n = self.u64()?; + check_count(n, self.cap(item_bytes)) + } + + /// Most items of `item_bytes` each the rest of the data can hold (0: [`MAX_ITEMS`]). + fn cap(&self, item_bytes: usize) -> usize { + self.remaining().checked_div(item_bytes).map_or(MAX_ITEMS, |n| n.min(MAX_ITEMS)) + } + + fn seek(&mut self, pos: u64) -> Result<()> { + self.pos = usize::try_from(pos).ok().filter(|p| *p <= self.b.len()).ok_or_else(truncated)?; + Ok(()) + } + + /// Follow a relative int64 offset stored at the cursor (Crate's nested values). + fn jump(&mut self) -> Result<()> { + let start = self.pos as u64; + let off = i64::from_le_bytes(self.array()?); + self.seek(start.checked_add_signed(off).filter(|_| off >= 8).ok_or_else(truncated)?) + } + + /// `n` integers of `width` bytes in the compressed integer coding. + fn ints(&mut self, n: usize, width: usize, budget: &mut Budget) -> Result> { + let size = self.u64()?; + let comp = self.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + if n == 0 { + return Ok(Vec::new()); + } + // LZ4 expands at most ~255x; a coded integer takes at least 2 bits. + if n > comp.len().saturating_mul(1024).saturating_add(64) { + return Err(SceneError::Malformed("integer array is larger than its compressed data allows".into())); + } + budget.take(n.saturating_mul(8))?; + let raw = decompress_block(comp, codec::encoded_ints_len(n, width))?; + decode_ints(&raw, n, width) + } +} + +/// A little-endian scalar from its `s.size()` bytes. +fn scalar(s: Scalar, b: &[u8]) -> f64 { + let mut a = [0u8; 8]; + for (o, v) in a.iter_mut().zip(b.iter().take(s.size())) { + *o = *v; + } + let le = u64::from_le_bytes(a); + match s { + Scalar::U8 => f64::from(le as u8), + Scalar::I32 => f64::from(le as u32 as i32), + Scalar::U32 => f64::from(le as u32), + Scalar::I64 => le as i64 as f64, + Scalar::U64 => le as f64, + Scalar::F16 => f64::from(half::f16::from_bits(le as u16).to_f32()), + Scalar::F32 => f64::from(f32::from_bits(le as u32)), + Scalar::F64 => f64::from_bits(le), + } +} + +fn is_quat(t: u8) -> bool { + (ty::QUATD..=ty::QUATH).contains(&t) +} + +/// Quaternions are stored imaginary first; values keep USD's text order (real first). +fn quat_order(t: u8, v: &mut [f64]) { + if is_quat(t) { + for q in v.as_chunks_mut::<4>().0 { + q.rotate_right(1); + } + } +} + +#[derive(Clone)] +struct PathEl { + text: String, + parent: Option, + name: String, + prop: bool, +} + +struct Crate<'a> { + b: &'a [u8], + ver: (u8, u8, u8), + tokens: Vec, + strings: Vec, + fields: Vec<(u32, u64)>, + fieldsets: Vec, + paths: Vec>, +} + +/// Parse a `.usdc` Crate binary layer, charging decoded allocations against `budget`. +pub fn read(bytes: &[u8], budget: &mut Budget) -> Result { + let mut boot = Cur { b: bytes, pos: 8 }; + let [major, minor, patch] = boot.array::<3>()?; + let ver = (major, minor, patch); + if ver < MIN_VERSION { + return Err(SceneError::Unsupported(format!("USD Crate version {major}.{minor}.{patch} (reads 0.4.0 and newer)"))); + } + boot.seek(16)?; + let mut toc = Cur { b: bytes, pos: 0 }; + toc.seek(boot.u64()?)?; + let n = toc.count(32)?.min(MAX_SECTIONS); + let mut sections = HashMap::new(); + for _ in 0..n { + let name = toc.array::<16>()?; + let name = String::from_utf8_lossy(name.split(|&c| c == 0).next().unwrap_or_default()).into_owned(); + let (start, size) = (toc.u64()?, toc.u64()?); + let end = start.checked_add(size).filter(|e| *e <= bytes.len() as u64).ok_or_else(truncated)?; + sections.insert(name, bytes.get(start as usize..end as usize).ok_or_else(truncated)?); + } + let section = |name: &str| sections.get(name).map(|b| Cur { b, pos: 0 }).ok_or_else(|| SceneError::Malformed(format!("missing {name} section"))); + let mut c = Crate { b: bytes, ver, tokens: Vec::new(), strings: Vec::new(), fields: Vec::new(), fieldsets: Vec::new(), paths: Vec::new() }; + c.read_tokens(section("TOKENS")?, budget)?; + if let Ok(mut s) = section("STRINGS") { + let n = s.count(4)?; + c.strings = (0..n).map(|_| s.u32()).collect::>()?; + } + c.read_fields(section("FIELDS")?, budget)?; + let mut s = section("FIELDSETS")?; + let n = s.count(0)?; + c.fieldsets = s.ints(n, 4, budget)?.into_iter().map(|v| v as u32).collect(); + c.read_paths(section("PATHS")?, budget)?; + let mut s = section("SPECS")?; + let n = s.count(0)?; + let (paths, sets, kinds) = (s.ints(n, 4, budget)?, s.ints(n, 4, budget)?, s.ints(n, 4, budget)?); + c.build(paths.iter().zip(&sets).zip(&kinds).map(|((p, f), k)| (*p as u32 as usize, *f as u32 as usize, *k)), budget) +} + +impl<'a> Crate<'a> { + fn token(&self, i: u64) -> Result<&str> { + usize::try_from(i) + .ok() + .and_then(|i| self.tokens.get(i)) + .map(String::as_str) + .ok_or_else(|| SceneError::Malformed(format!("token index {i} out of range"))) + } + + fn string(&self, i: u32) -> Result<&str> { + let t = self.strings.get(i as usize).ok_or_else(|| SceneError::Malformed(format!("string index {i} out of range")))?; + self.token(u64::from(*t)) + } + + fn path(&self, i: u32) -> Result<&PathEl> { + self.paths.get(i as usize).and_then(Option::as_ref).ok_or_else(|| SceneError::Malformed(format!("path index {i} out of range"))) + } + + fn read_tokens(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { + let n = s.u64()?; + let (raw_len, comp_len) = (s.u64()?, s.u64()?); + let raw_len = check_count(raw_len, MAX_ITEMS)?; + let n = check_count(n, raw_len)?; + budget.take(raw_len.saturating_add(n.saturating_mul(24)))?; + let comp = s.bytes(usize::try_from(comp_len).map_err(|_| truncated())?)?; + let raw = decompress_block(comp, raw_len)?; + self.tokens = raw.split(|&c| c == 0).take(n).map(|t| String::from_utf8_lossy(t).into_owned()).collect(); + if self.tokens.len() < n { + return Err(SceneError::Malformed("fewer tokens than declared".into())); + } + Ok(()) + } + + fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let count = section.count(0)?; + let tokens = section.ints(count, 4, budget)?; + let size = section.u64()?; + let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + budget.take(count.saturating_mul(24))?; + let representations = decompress_block(compressed, count.saturating_mul(8))?; + if representations.len() != count * 8 { + return Err(SceneError::Malformed("field values are truncated".into())); + } + + self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + + Ok(()) + } + + fn decode_path_element(&self, parent: Option, element_token: i64, budget: &mut Budget) -> Result { + let Some(parent_index) = parent else { + return Ok(PathEl { text: "/".into(), parent: None, name: String::new(), prop: false }); + }; + let path_error = || SceneError::Malformed("corrupt path table".into()); + let name = self.token(element_token.unsigned_abs())?; + let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?; + let separator_bytes = usize::from(element_token < 0 || (!name.starts_with('{') && parent_path != "/")); + let text_bytes = parent_path.len().saturating_add(name.len()).saturating_add(separator_bytes); + + // Charge both retained strings before allocating either one + budget.take(text_bytes.saturating_add(name.len()))?; + let name = name.to_string(); + let text = match (element_token < 0, parent_path) { + (true, _) => format!("{parent_path}.{name}"), + (false, _) if name.starts_with('{') => format!("{parent_path}{name}"), + (false, "/") => format!("/{name}"), + (false, _) => format!("{parent_path}/{name}"), + }; + Ok(PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 }) + } + + /// Paths are stored as a pre-order tree: element token (negative for properties) and a + /// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump). + fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let path_count = section.count(0)?; + let encoded_count = section.count(0)?; + let path_indices = section.ints(encoded_count, 4, budget)?; + let elements = section.ints(encoded_count, 4, budget)?; + let jumps = section.ints(encoded_count, 4, budget)?; + if path_count > MAX_PATHS { + return Err(SceneError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})"))); + } + + // Charge slot storage before allocating the table + budget.take(path_count.saturating_mul(std::mem::size_of::>()))?; + self.paths = vec![None; path_count]; + let mut pending_branches: Vec<(usize, Option)> = vec![(0, None)]; + let mut visited_count = 0usize; + let path_error = || SceneError::Malformed("corrupt path table".into()); + while let Some((mut cursor_index, mut parent)) = pending_branches.pop() { + loop { + visited_count += 1; + if visited_count > encoded_count { + return Err(path_error()); + } + + let node_index = cursor_index; + cursor_index += 1; + let path_index = path_indices + .get(node_index) + .map(|v| *v as u32 as usize) + .filter(|parent_index| *parent_index < path_count) + .ok_or_else(path_error)?; + let element_token = if parent.is_some() { *elements.get(node_index).ok_or_else(path_error)? } else { 0 }; + let path_element = self.decode_path_element(parent, element_token, budget)?; + + if let Some(slot) = self.paths.get_mut(path_index) { + *slot = Some(path_element); + } + + let jump = *jumps.get(node_index).ok_or_else(path_error)?; + let (child, sibling) = (jump > 0 || jump == -1, jump >= 0); + if child { + if sibling { + pending_branches + .push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent)); + } + parent = Some(path_index); + } + if !child && !sibling { + break; + } + } + } + + Ok(()) + } + + /// (name, value rep) of the fields of field set `set`. + fn fields_of(&self, set: usize) -> Vec<(&str, u64)> { + self.fieldsets + .get(set..) + .unwrap_or_default() + .iter() + .take_while(|f| **f != u32::MAX) + .filter_map(|f| self.fields.get(*f as usize)) + .filter_map(|(t, rep)| Some((self.token(u64::from(*t)).ok()?, *rep))) + .collect() + } + + fn build_pseudo_root( + &self, + layer: &mut Layer, + prims: &mut HashMap, + path: usize, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + prims.insert(path, 0); + for &(name, rep) in fields { + match name { + "metersPerUnit" => layer.meters_per_unit = self.number(rep, budget)?, + "upAxis" => layer.up_axis = self.tokens_of(rep, budget)?.into_iter().next(), + "subLayers" => layer.warn("sublayers are not loaded"), + _ => {} + } + } + Ok(()) + } + + fn build_prim( + &self, + layer: &mut Layer, + prims: &mut HashMap, + path: usize, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + let Some(id) = self.prim(layer, prims, path, 0) else { return Ok(()) }; + let mut spec = std::mem::take(layer.prims.get_mut(id).ok_or_else(truncated)?); + for &(name, rep) in fields { + match name { + "typeName" => spec.type_name = self.tokens_of(rep, budget)?.into_iter().next().unwrap_or_default(), + "specifier" => { + spec.specifier = match self.value(rep, budget)? { + Some(Val::Num(v)) if v.first() == Some(&1.0) => Specifier::Over, + Some(Val::Num(v)) if v.first() == Some(&2.0) => Specifier::Class, + _ => Specifier::Def, + } + } + "active" => spec.active = self.number(rep, budget)?.map(|v| v != 0.0), + "references" => { + let (internal, external) = self.references(rep)?; + spec.references.extend(internal); + if external { + layer.warn("external references and payloads are not loaded"); + } + } + "payload" => layer.warn("external references and payloads are not loaded"), + _ => {} + } + } + if let Some(slot) = layer.prims.get_mut(id) { + *slot = spec; + } + Ok(()) + } + + fn build_prop( + &self, + layer: &mut Layer, + prims: &mut HashMap, + el: &PathEl, + kind: i64, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + let Some(owner) = el.parent.filter(|_| el.prop).and_then(|p| self.prim(layer, prims, p, 0)) else { return Ok(()) }; + let mut prop = Prop { type_name: if kind == SPEC_RELATIONSHIP { "rel".into() } else { String::new() }, ..Prop::default() }; + let mut samples = None; + for &(name, rep) in fields { + match name { + "typeName" => prop.type_name = self.tokens_of(rep, budget)?.into_iter().next().unwrap_or_default(), + "default" | "targetPaths" => prop.value = self.value(rep, budget)?, + "connectionPaths" => { + if let Some(Val::Path(p)) = self.value(rep, budget)? { + prop.connect = p.into_iter().next(); + } + } + "timeSamples" => samples = Some(rep), + "interpolation" => prop.interpolation = self.tokens_of(rep, budget)?.into_iter().next(), + _ => {} + } + } + if prop.value.is_none() + && let Some(rep) = samples + { + prop.value = self.value(rep, budget)?; + } + if let Some(spec) = layer.prims.get_mut(owner) { + spec.props.insert(el.name.clone(), prop); + } + Ok(()) + } + + fn build(&self, specs: impl Iterator, budget: &mut Budget) -> Result { + let mut layer = Layer::new(); + let mut prims: HashMap = HashMap::new(); + for (path, set, kind) in specs { + let Some(el) = self.paths.get(path).and_then(Option::as_ref) else { + return Err(SceneError::Malformed(format!("spec path {path} out of range"))); + }; + let fields = self.fields_of(set); + match kind { + SPEC_PSEUDO_ROOT => self.build_pseudo_root(&mut layer, &mut prims, path, &fields, budget)?, + SPEC_PRIM => self.build_prim(&mut layer, &mut prims, path, &fields, budget)?, + SPEC_ATTRIBUTE | SPEC_RELATIONSHIP => self.build_prop(&mut layer, &mut prims, el, kind, &fields, budget)?, + SPEC_VARIANT | SPEC_VARIANT_SET => layer.warn("variant sets are not applied"), + _ => {} + } + } + Ok(layer) + } + + /// The layer prim of prim path `path`, created (with its ancestors) on first use; None for + /// paths inside variants or nested deeper than [`MAX_DEPTH`]. + fn prim(&self, layer: &mut Layer, prims: &mut HashMap, path: usize, depth: usize) -> Option { + if let Some(id) = prims.get(&path) { + return Some(*id); + } + let el = self.paths.get(path)?.as_ref()?; + if el.prop || el.name.starts_with('{') || depth > MAX_DEPTH { + return None; + } + let parent = match el.parent { + Some(p) if self.paths.get(p)?.as_ref()?.parent.is_none() => 0, + Some(p) => self.prim(layer, prims, p, depth + 1)?, + None => return Some(0), + }; + let id = layer.add_prim(parent, &el.name); + prims.insert(path, id); + Some(id) + } + + fn number(&self, rep: u64, budget: &mut Budget) -> Result> { + Ok(match self.value(rep, budget)? { + Some(Val::Num(v)) => v.first().copied(), + _ => None, + }) + } + + fn tokens_of(&self, rep: u64, budget: &mut Budget) -> Result> { + Ok(match self.value(rep, budget)? { + Some(Val::Tok(v)) => v, + _ => Vec::new(), + }) + } + + fn at(&self, offset: u64) -> Result> { + let mut c = Cur { b: self.b, pos: 0 }; + c.seek(offset)?; + Ok(c) + } + + fn strings_from_ids(&self, t: u8, ids: Vec, budget: &mut Budget) -> Result> { + ids.into_iter() + .map(|i| { + let s = match t { + ty::STRING => self.string(i), + _ => self.token(u64::from(i)), + }? + .to_string(); + budget.take(s.len() + 24)?; + Ok(s) + }) + .collect() + } + + /// Decode a value rep; None for types a neutral layer does not need. + fn value(&self, rep: u64, budget: &mut Budget) -> Result> { + self.value_at_depth(rep, budget, 0) + } + + fn value_at_depth(&self, rep: u64, budget: &mut Budget, depth: usize) -> Result> { + let t = ((rep >> 48) & 0xFF) as u8; + let payload = rep & codec::PAYLOAD_MASK; + let (array, inlined, compressed) = (rep & codec::IS_ARRAY != 0, rep & codec::IS_INLINED != 0, rep & codec::IS_COMPRESSED != 0); + if rep & codec::IS_ARRAY_EDIT != 0 { + return Ok(None); + } + if array && inlined { + return Ok(Some(Val::Num(Vec::new()))); + } + Ok(Some(match t { + ty::STRING | ty::TOKEN | ty::ASSET_PATH if !array => Val::Tok(self.strings_from_ids(t, vec![payload as u32], budget)?), + ty::STRING | ty::TOKEN | ty::ASSET_PATH => { + let mut c = self.at(payload)?; + let ids = self.array_header(&mut c, 4)?; + Val::Tok(self.strings_from_ids(t, (0..ids).map(|_| c.u32()).collect::>()?, budget)?) + } + ty::SPECIFIER | ty::VARIABILITY | ty::PERMISSION => Val::Num(vec![f64::from(payload as u32)]), + ty::TOKEN_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(4)?; + Val::Tok(self.strings_from_ids(t, (0..n).map(|_| c.u32()).collect::>()?, budget)?) + } + ty::PATH_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(4)?; + Val::Path((0..n).map(|_| Ok(self.path(c.u32()?)?.text.clone())).collect::>()?) + } + ty::PATH_LIST_OP => Val::Path(self.list_op(payload)?.into_iter().map(|i| Ok(self.path(i)?.text.clone())).collect::>()?), + ty::TOKEN_LIST_OP => Val::Tok(self.strings_from_ids(t, self.list_op(payload)?, budget)?), + ty::DOUBLE_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(8)?; + budget.take(n * 8)?; + Val::Num((0..n).map(|_| c.f64()).collect::>()?) + } + ty::TIME_SAMPLES if depth == 0 => { + let mut c = self.at(payload)?; + c.jump()?; + c.u64()?; + c.jump()?; + if c.u64()? == 0 { + return Ok(None); + } + return self.value_at_depth(c.u64()?, budget, 1); + } + _ => match codec::numeric(t) { + Some((s, comps)) if inlined => Val::Num(inline_numeric(t, s, comps, payload)), + Some((s, comps)) if array => self.numeric_array(t, s, comps, payload, compressed, budget)?, + Some((s, comps)) => { + let mut c = self.at(payload)?; + let raw = c.bytes(s.size() * comps)?; + let mut v: Vec = raw.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + quat_order(t, &mut v); + Val::Num(v) + } + None => return Ok(None), + }, + })) + } + + /// Element count of an array at `c` (`elem` bytes each), past the pre-0.5 shape word. + fn array_header(&self, c: &mut Cur, elem: usize) -> Result { + if self.ver < (0, 5, 0) { + c.u32()?; + } + let n = if self.ver < (0, 7, 0) { u64::from(c.u32()?) } else { c.u64()? }; + check_count(n, c.cap(elem)) + } + + fn numeric_array(&self, t: u8, s: Scalar, comps: usize, payload: u64, compressed: bool, budget: &mut Budget) -> Result { + let mut c = self.at(payload)?; + let int = matches!(s, Scalar::I32 | Scalar::U32 | Scalar::I64 | Scalar::U64) && comps == 1 && self.ver >= (0, 5, 0); + let float = matches!(s, Scalar::F16 | Scalar::F32 | Scalar::F64) && comps == 1 && self.ver >= (0, 6, 0); + let packed = compressed && (int || float); + let n = self.array_header(&mut c, if packed { 0 } else { s.size() * comps })?; + budget.take(n.saturating_mul(comps).saturating_mul(8))?; + if packed && n >= codec::MIN_COMPRESSED_ARRAY { + let as_f64 = |v: i64| match s { + Scalar::U32 => f64::from(v as u32), + Scalar::U64 => v as u64 as f64, + _ => v as f64, + }; + if int { + let width = s.size(); + return Ok(Val::Num(c.ints(n, width, budget)?.into_iter().map(as_f64).collect())); + } + return Ok(Val::Num(match c.u8()? { + b'i' => c.ints(n, 4, budget)?.into_iter().map(|v| v as f64).collect(), + b't' => { + let lut_len = c.u32()? as usize; + let lut: Vec = + c.bytes(lut_len.checked_mul(s.size()).ok_or_else(truncated)?)?.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + let idx = c.ints(n, 4, budget)?; + idx.into_iter() + .map(|i| lut.get(i as u32 as usize).copied().ok_or_else(|| SceneError::Malformed("lookup table index out of range".into()))) + .collect::>()? + } + code => return Err(SceneError::Malformed(format!("unknown float array coding {code}"))), + })); + } + let raw = c.bytes(n.checked_mul(comps).and_then(|k| k.checked_mul(s.size())).ok_or_else(truncated)?)?; + let mut v: Vec = raw.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + quat_order(t, &mut v); + Ok(Val::Num(v)) + } + + /// The kept items (explicit, added, prepended, appended) of a token or path list op. + fn list_op(&self, payload: u64) -> Result> { + let mut c = self.at(payload)?; + let header = c.u8()?; + let mut out = Vec::new(); + // Lists in file order: explicit, added, prepended, appended, deleted, ordered. + for bit in [1, 2, 5, 6, 3, 4] { + if header & (1 << bit) == 0 { + continue; + } + let n = c.count(4)?; + let items: Vec = (0..n).map(|_| c.u32()).collect::>()?; + if bit <= 2 || bit >= 5 { + out.extend(items); + } + } + Ok(out) + } + + fn skip_custom_data(c: &mut Cur<'_>) -> Result<()> { + let entries = c.count(12)?; + for _ in 0..entries { + c.u32()?; + c.jump()?; + c.u64()?; + } + Ok(()) + } + + /// Internal reference targets of a reference list op, and whether any was external. + fn references(&self, rep: u64) -> Result<(Vec, bool)> { + if ((rep >> 48) & 0xFF) as u8 != ty::REFERENCE_LIST_OP || rep & codec::IS_INLINED != 0 { + return Ok((Vec::new(), false)); + } + let mut c = self.at(rep & codec::PAYLOAD_MASK)?; + let header = c.u8()?; + let (mut internal, mut external) = (Vec::new(), false); + for bit in [1, 2, 5, 6, 3, 4] { + if header & (1 << bit) == 0 { + continue; + } + let n = c.count(28)?; + for _ in 0..n { + let asset = self.string(c.u32()?)?.to_string(); + let prim = self.path(c.u32()?)?.text.clone(); + c.f64()?; + c.f64()?; + Self::skip_custom_data(&mut c)?; + if bit == 3 || bit == 4 { + continue; + } + match (asset.is_empty(), prim.as_str()) { + (true, p) if p != "/" && !p.is_empty() => internal.push(prim), + _ => external = true, + } + } + } + Ok((internal, external)) + } +} + +/// A numeric value stored in the rep itself: 32-bit scalars (doubles as floats, 64-bit ints as +/// 32-bit), vectors as int8 components and matrices as int8 diagonals. +fn inline_numeric(t: u8, s: Scalar, comps: usize, payload: u64) -> Vec { + let bytes = payload.to_le_bytes(); + let i8s = |n: usize| bytes.iter().take(n).map(|b| f64::from(*b as i8)).collect::>(); + match (t, comps) { + (ty::MATRIX2D..=ty::MATRIX4D, _) => { + let dim = usize::from(t - ty::MATRIX2D) + 2; + let diag = i8s(dim); + (0..dim * dim).map(|k| if k % (dim + 1) == 0 { diag.get(k / (dim + 1)).copied().unwrap_or(1.0) } else { 0.0 }).collect() + } + (_, 1) => vec![match s { + Scalar::U8 => f64::from(payload as u8), + Scalar::I32 | Scalar::I64 => f64::from(payload as u32 as i32), + Scalar::U32 | Scalar::U64 => f64::from(payload as u32), + Scalar::F16 => f64::from(half::f16::from_bits(payload as u16).to_f32()), + Scalar::F32 | Scalar::F64 => f64::from(f32::from_bits(payload as u32)), + }], + _ => i8s(comps), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::{Crate, Cur, PathEl, Scalar, inline_numeric}; + use crate::codec::{self, ty}; + use crate::compress; + use crate::integers::{self, Width}; + use crate::scene::{Budget, MAX_DECODED_BYTES, SceneError, Val}; + + fn crate_over(b: &[u8], ver: (u8, u8, u8)) -> Crate<'_> { + Crate { b, ver, tokens: Vec::new(), strings: Vec::new(), fields: Vec::new(), fieldsets: Vec::new(), paths: Vec::new() } + } + + fn compressed_ints(out: &mut Vec, v: &[i64]) { + let comp = compress::compress(&integers::encode(v, Width::I32, MAX_DECODED_BYTES).unwrap(), MAX_DECODED_BYTES).unwrap(); + out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + out.extend_from_slice(&comp); + } + + #[test] + fn repeated_path_names_count_toward_the_decode_budget() { + let name = "long_name_reused"; + let mut section = Vec::new(); + section.extend_from_slice(&3u64.to_le_bytes()); + section.extend_from_slice(&3u64.to_le_bytes()); + compressed_ints(&mut section, &[0, 1, 2]); + compressed_ints(&mut section, &[0, 0, 0]); + compressed_ints(&mut section, &[-1, 0, -2]); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + + let decoded_arrays_bytes = 3 * 3 * std::mem::size_of::(); + let path_slots_bytes = 3 * std::mem::size_of::>(); + let path_text_bytes = 2 * (1 + name.len()); + let one_name_budget = decoded_arrays_bytes + path_slots_bytes + path_text_bytes + name.len(); + let mut insufficient_budget = Budget(one_name_budget); + + let rejected = crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut insufficient_budget); + + assert!(matches!(rejected, Err(SceneError::TooLarge(_))), "two path names cannot fit a one-name budget"); + drop(crate_data); + + let mut complete_budget = Budget(one_name_budget + name.len()); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut complete_budget).unwrap(); + + assert_eq!(complete_budget.0, 0); + assert_eq!(crate_data.path(1).unwrap().text, format!("/{name}")); + assert_eq!(crate_data.path(2).unwrap().text, format!("/{name}")); + } + + #[test] + fn compressed_float_and_int_arrays() { + let n = 20usize; + let mut b = Vec::new(); + // 'i': integral floats as compressed ints. + b.extend_from_slice(&(n as u64).to_le_bytes()); + b.push(b'i'); + let ints: Vec = (0..n as i64).map(|i| i * 3 - 7).collect(); + compressed_ints(&mut b, &ints); + let lut_at = b.len() as u64; + // 't': a lookup table of doubles and compressed indexes into it. + b.extend_from_slice(&(n as u64).to_le_bytes()); + b.push(b't'); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(&0.25f64.to_le_bytes()); + b.extend_from_slice(&(-8.5f64).to_le_bytes()); + let idx: Vec = (0..n as i64).map(|i| i % 2).collect(); + compressed_ints(&mut b, &idx); + let i64_at = b.len() as u64; + b.extend_from_slice(&(n as u64).to_le_bytes()); + let comp = compress::compress( + &integers::encode(&(0..n as i64).map(|i| i << 33).collect::>(), Width::I64, MAX_DECODED_BYTES).unwrap(), + MAX_DECODED_BYTES, + ) + .unwrap(); + b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + b.extend_from_slice(&comp); + let c = crate_over(&b, (0, 8, 0)); + let mut budget = Budget::new(); + let f32s = c.numeric_array(ty::FLOAT, Scalar::F32, 1, 0, true, &mut budget).unwrap(); + assert_eq!(f32s, Val::Num(ints.iter().map(|&i| i as f64).collect())); + let lut = c.numeric_array(ty::DOUBLE, Scalar::F64, 1, lut_at, true, &mut budget).unwrap(); + assert_eq!(lut, Val::Num((0..n).map(|i| if i % 2 == 0 { 0.25 } else { -8.5 }).collect())); + let wide = c.numeric_array(ty::INT64, Scalar::I64, 1, i64_at, true, &mut budget).unwrap(); + assert_eq!(wide, Val::Num((0..n as i64).map(|i| (i << 33) as f64).collect())); + // Out-of-range lookups and unknown codings are errors. + let mut bad = b.clone(); + bad[lut_at as usize + 8] = b'x'; + assert!(crate_over(&bad, (0, 8, 0)).numeric_array(ty::DOUBLE, Scalar::F64, 1, lut_at, true, &mut budget).is_err()); + } + + #[test] + fn old_array_headers_halves_quats_and_inlined_values() { + // 0.4: discarded shape word and a u32 count; half floats. + let mut b = Vec::new(); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + for v in [1.5f32, -2.0] { + b.extend_from_slice(&half::f16::from_f32(v).to_bits().to_le_bytes()); + } + let quat_at = b.len() as u64; + for v in [0.0f32, 0.0, 1.0, 0.5] { + b.extend_from_slice(&v.to_le_bytes()); + } + let c = crate_over(&b, (0, 4, 0)); + let mut budget = Budget::new(); + assert_eq!(c.numeric_array(ty::HALF, Scalar::F16, 1, 0, false, &mut budget).unwrap(), Val::Num(vec![1.5, -2.0])); + let quat = c.value((17u64 << 48) | quat_at, &mut budget).unwrap(); + assert_eq!(quat, Some(Val::Num(vec![0.5, 0.0, 0.0, 1.0])), "quaternions read real first"); + assert_eq!(inline_numeric(ty::MATRIX2D, Scalar::F64, 4, 0x0302), vec![2.0, 0.0, 0.0, 3.0]); + assert_eq!(inline_numeric(24, Scalar::F32, 3, 0x00FF_0201), vec![1.0, 2.0, -1.0]); + assert_eq!(inline_numeric(ty::DOUBLE, Scalar::F64, 1, u64::from(0.5f32.to_bits())), vec![0.5]); + assert_eq!(inline_numeric(ty::INT, Scalar::I32, 1, u64::from((-3i32) as u32)), vec![-3.0]); + // Array edits are not applied; empty arrays are inlined. + assert_eq!(c.value(codec::IS_ARRAY_EDIT | (3u64 << 48), &mut budget).unwrap(), None); + assert_eq!(c.value(codec::IS_ARRAY | codec::IS_INLINED | (3u64 << 48), &mut budget).unwrap(), Some(Val::Num(vec![]))); + } +} diff --git a/crates/usd/src/scene/write.rs b/crates/usd/src/scene/write.rs new file mode 100644 index 000000000..53470d518 --- /dev/null +++ b/crates/usd/src/scene/write.rs @@ -0,0 +1,662 @@ +//! Writers for neutral [`UsdLayer`] scenes: `.usda` text and `.usdc` Crate binary (0.8.0). + +use std::collections::HashMap; +use std::fmt::Write as _; + +use crate::codec::{self, ty}; +use crate::compress; +use crate::integers::{self, Width}; +use crate::scene::{MAX_DECODED_BYTES, Result, SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue}; + +const VERSION: [u8; 3] = [0, 8, 0]; +const SPEC_ATTRIBUTE: i64 = 1; +const SPEC_PRIM: i64 = 6; +const SPEC_PSEUDO_ROOT: i64 = 7; +const SPEC_RELATIONSHIP: i64 = 8; +/// List-op header bits. +const LIST_EXPLICIT: u8 = 0b11; +const LIST_PREPENDED: u8 = 1 << 5; + +fn rep(t: u8, flags: u64, payload: u64) -> u64 { + (u64::from(t) << 48) | flags | (payload & codec::PAYLOAD_MASK) +} + +fn compress_block(input: &[u8]) -> Result> { + compress::compress(input, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +fn encode_ints(values: &[i64]) -> Result> { + integers::encode(values, Width::I32, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +/// Text of a value as `.usda` writes it. +fn usda_value(s: &mut String, v: &UsdValue) { + let tuple = |s: &mut String, c: &[f32]| { + s.push('('); + for (i, x) in c.iter().enumerate() { + let _ = write!(s, "{}{x}", if i > 0 { ", " } else { "" }); + } + s.push(')'); + }; + let list = |s: &mut String, n: usize, item: &mut dyn FnMut(&mut String, usize)| { + s.push('['); + for i in 0..n { + if i > 0 { + s.push_str(", "); + } + item(s, i); + } + s.push(']'); + }; + match v { + UsdValue::Token(t) | UsdValue::Str(t) => { + let _ = write!(s, "\"{t}\""); + } + UsdValue::Int(i) => { + let _ = write!(s, "{i}"); + } + UsdValue::Double(d) => { + let _ = write!(s, "{d}"); + } + UsdValue::Asset(a) => { + let _ = write!(s, "@{a}@"); + } + UsdValue::Target(p) => { + let _ = write!(s, "<{p}>"); + } + UsdValue::Float4(c) => tuple(s, c), + UsdValue::Ints(v) => list(s, v.len(), &mut |s, i| { + let _ = write!(s, "{}", v.get(i).copied().unwrap_or_default()); + }), + UsdValue::Vec2fs(v) => list(s, v.len(), &mut |s, i| tuple(s, v.get(i).map_or(&[][..], |x| &x[..]))), + UsdValue::Vec3fs(v) => list(s, v.len(), &mut |s, i| tuple(s, v.get(i).map_or(&[][..], |x| &x[..]))), + } +} + +fn usda_prim(s: &mut String, p: &UsdPrim, depth: usize) { + let pad = " ".repeat(depth); + let _ = write!(s, "\n{pad}def {} \"{}\"", p.type_name, p.name); + if p.binding_api { + let _ = write!(s, " (\n{pad} prepend apiSchemas = [\"MaterialBindingAPI\"]\n{pad})"); + } + let _ = writeln!(s, "\n{pad}{{"); + for a in &p.attrs { + s.push_str(&pad); + s.push_str(" "); + if a.type_name == "rel" { + let _ = write!(s, "rel {}", a.name); + } else { + let _ = write!(s, "{}{} {}", if a.uniform { "uniform " } else { "" }, a.type_name, a.name); + } + if let Some(c) = &a.connect { + let _ = write!(s, ".connect = <{c}>"); + } else if let Some(v) = &a.value { + s.push_str(" = "); + usda_value(s, v); + } + if let Some(i) = &a.interpolation { + let _ = write!(s, " (\n{pad} interpolation = \"{i}\"\n{pad} )"); + } + s.push('\n'); + } + for c in &p.children { + usda_prim(s, c, depth + 1); + } + let _ = writeln!(s, "{pad}}}"); +} + +/// Format `layer` as `.usda` text. +pub fn usda(layer: &UsdLayer) -> String { + let mut s = format!("#usda 1.0\n(\n defaultPrim = \"{}\"\n", layer.root.name); + if let Some(doc) = &layer.doc { + let _ = writeln!(s, " doc = \"{doc}\""); + } + let _ = writeln!(s, " metersPerUnit = {}\n upAxis = \"{}\"\n)", layer.meters_per_unit, layer.up_axis); + usda_prim(&mut s, &layer.root, 0); + s +} + +struct Node { + token: u32, + prop: bool, + children: Vec, +} + +#[derive(Default)] +struct Writer { + out: Vec, + tokens: Vec, + token_ids: HashMap, + /// String table: token index per string. + strings: Vec, + fields: Vec<(u32, u64)>, + field_ids: HashMap<(u32, u64), u32>, + fieldsets: Vec, + fieldset_ids: HashMap, u32>, + /// Path tree (index 0 is the root). + paths: Vec, + path_ids: HashMap, + specs: Vec<[i64; 3]>, +} + +impl Writer { + /// The bootstrap header and the root path; values follow. + fn new() -> Writer { + let mut w = Writer::default(); + // Token 0 must never name a property (properties store their token negated). + w.token("Xform"); + w.paths.push(Node { token: 0, prop: false, children: Vec::new() }); + w.path_ids.insert("/".into(), 0); + w.out.extend_from_slice(codec::MAGIC); + w.out.extend_from_slice(&VERSION); + w.out.resize(codec::BOOTSTRAP_LEN, 0); + w + } + + fn token(&mut self, s: &str) -> u32 { + if let Some(&i) = self.token_ids.get(s) { + return i; + } + let i = self.tokens.len() as u32; + self.tokens.push(s.into()); + self.token_ids.insert(s.into(), i); + i + } + + /// Index of `s` in the string table (which holds token indices). + fn string(&mut self, s: &str) -> u32 { + let t = self.token(s); + match self.strings.iter().position(|x| *x == t) { + Some(i) => i as u32, + None => { + self.strings.push(t); + (self.strings.len() - 1) as u32 + } + } + } + + fn add_path(&mut self, parent: usize, parent_text: &str, name: &str, prop: bool) -> (usize, String) { + let text = match (prop, parent_text) { + (true, _) => format!("{parent_text}.{name}"), + (false, "/") => format!("/{name}"), + _ => format!("{parent_text}/{name}"), + }; + let id = self.paths.len(); + let token = self.token(name); + self.paths.push(Node { token, prop, children: Vec::new() }); + if let Some(p) = self.paths.get_mut(parent) { + p.children.push(id); + } + self.path_ids.insert(text.clone(), id); + (id, text) + } + + /// Pre-order path nodes of `p` (attributes before child prims). + fn add_prim_paths(&mut self, parent: usize, parent_text: &str, p: &UsdPrim) { + let (id, text) = self.add_path(parent, parent_text, &p.name, false); + for a in &p.attrs { + self.add_path(id, &text, &a.name, true); + } + for c in &p.children { + self.add_prim_paths(id, &text, c); + } + } + + fn path_id(&self, path: &str) -> Result { + self.path_ids.get(path).map(|&i| i as u32).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {path}"))) + } + + fn offset(&self) -> u64 { + self.out.len() as u64 + } + + fn u32s(&mut self, v: impl Iterator) { + for x in v { + self.out.extend_from_slice(&x.to_le_bytes()); + } + } + + fn list_op(&mut self, t: u8, header: u8, items: &[u32]) -> u64 { + let at = self.offset(); + self.out.push(header); + self.out.extend_from_slice(&(items.len() as u64).to_le_bytes()); + self.u32s(items.iter().copied()); + rep(t, 0, at) + } + + fn token_vector(&mut self, names: &[&str]) -> u64 { + let ids: Vec = names.iter().map(|n| self.token(n)).collect(); + let at = self.offset(); + self.out.extend_from_slice(&(ids.len() as u64).to_le_bytes()); + self.u32s(ids.into_iter()); + rep(ty::TOKEN_VECTOR, 0, at) + } + + /// An array of `n` elements whose little-endian bytes are `bytes`. + fn raw_array(&mut self, t: u8, n: usize, bytes: impl Iterator) -> u64 { + let at = self.offset(); + self.out.extend_from_slice(&(n as u64).to_le_bytes()); + self.out.extend(bytes); + rep(t, codec::IS_ARRAY, at) + } + + fn value(&mut self, v: &UsdValue) -> Result { + let floats = |v: &mut dyn Iterator| v.flat_map(f32::to_le_bytes).collect::>(); + Ok(match v { + UsdValue::Token(t) => rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(t))), + UsdValue::Asset(a) => rep(ty::ASSET_PATH, codec::IS_INLINED, u64::from(self.token(a))), + UsdValue::Str(s) => rep(ty::STRING, codec::IS_INLINED, u64::from(self.string(s))), + UsdValue::Int(i) => rep(ty::INT, codec::IS_INLINED, u64::from(*i as u32)), + UsdValue::Double(d) => { + let at = self.offset(); + self.out.extend_from_slice(&d.to_le_bytes()); + rep(ty::DOUBLE, 0, at) + } + UsdValue::Float4(c) => { + let at = self.offset(); + self.out.extend(floats(&mut c.iter().copied())); + rep(ty::VEC4F, 0, at) + } + UsdValue::Ints(v) if v.len() >= codec::MIN_COMPRESSED_ARRAY => { + let at = self.offset(); + self.out.extend_from_slice(&(v.len() as u64).to_le_bytes()); + self.ints(&v.iter().map(|&i| i64::from(i)).collect::>())?; + rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at) + } + UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())), + UsdValue::Vec2fs(v) => { + let bytes = floats(&mut v.iter().flatten().copied()); + self.raw_array(ty::VEC2F, v.len(), bytes.into_iter()) + } + UsdValue::Vec3fs(v) => { + let bytes = floats(&mut v.iter().flatten().copied()); + self.raw_array(ty::VEC3F, v.len(), bytes.into_iter()) + } + UsdValue::Target(p) => { + let id = self.path_id(p)?; + self.list_op(ty::PATH_LIST_OP, LIST_EXPLICIT, &[id]) + } + }) + } + + /// Compressed integers: their compressed size, then the LZ4-framed coding. + fn ints(&mut self, v: &[i64]) -> Result<()> { + let comp = compress_block(&encode_ints(v)?)?; + self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + self.out.extend_from_slice(&comp); + Ok(()) + } + + fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) { + let ids: Vec = fields + .into_iter() + .map(|(name, value)| { + let key = (self.token(name), value); + let next = self.fields.len() as u32; + *self.field_ids.entry(key).or_insert_with(|| { + self.fields.push(key); + next + }) + }) + .collect(); + let set = match self.fieldset_ids.get(&ids) { + Some(&s) => s, + None => { + let s = self.fieldsets.len() as u32; + self.fieldsets.extend(ids.iter().map(|&i| i64::from(i))); + self.fieldsets.push(i64::from(u32::MAX)); + self.fieldset_ids.insert(ids, s); + s + } + }; + self.specs.push([path as i64, i64::from(set), kind]); + } + + fn prim_specs(&mut self, text: &str, p: &UsdPrim) -> Result<()> { + let id = *self.path_ids.get(text).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {text}")))?; + let mut fields = vec![ + ("specifier", rep(ty::SPECIFIER, codec::IS_INLINED, 0)), + ("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(&p.type_name)))), + ]; + if p.binding_api { + let api = self.token("MaterialBindingAPI"); + fields.push(("apiSchemas", self.list_op(ty::TOKEN_LIST_OP, LIST_PREPENDED, &[api]))); + } + if !p.attrs.is_empty() { + let names: Vec<&str> = p.attrs.iter().map(|a| a.name.as_str()).collect(); + fields.push(("properties", self.token_vector(&names))); + } + if !p.children.is_empty() { + let names: Vec<&str> = p.children.iter().map(|c| c.name.as_str()).collect(); + fields.push(("primChildren", self.token_vector(&names))); + } + self.spec(id, SPEC_PRIM, fields); + for a in &p.attrs { + self.attr_spec(&format!("{text}.{}", a.name), a)?; + } + for c in &p.children { + self.prim_specs(&format!("{text}/{}", c.name), c)?; + } + Ok(()) + } + + fn attr_spec(&mut self, text: &str, a: &UsdAttr) -> Result<()> { + let id = *self.path_ids.get(text).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {text}")))?; + let rel = a.type_name == "rel"; + let mut fields = vec![ + ("custom", rep(ty::BOOL, codec::IS_INLINED, 0)), + ("variability", rep(ty::VARIABILITY, codec::IS_INLINED, u64::from(rel || a.uniform))), + ]; + if !rel { + fields.push(("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(&a.type_name))))); + } + if let Some(c) = &a.connect { + let id = self.path_id(c)?; + fields.push(("connectionPaths", self.list_op(ty::PATH_LIST_OP, LIST_EXPLICIT, &[id]))); + } + if let Some(v) = &a.value { + fields.push((if rel { "targetPaths" } else { "default" }, self.value(v)?)); + } + if let Some(i) = &a.interpolation { + fields.push(("interpolation", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(i))))); + } + self.spec(id, if rel { SPEC_RELATIONSHIP } else { SPEC_ATTRIBUTE }, fields); + Ok(()) + } + + /// (path index, element token, jump) per node, in pre-order. + fn path_table(&self) -> [Vec; 3] { + let n = self.paths.len(); + let mut order = Vec::with_capacity(n); + let mut stack = vec![0usize]; + while let Some(i) = stack.pop() { + order.push(i); + stack.extend(self.paths.get(i).into_iter().flat_map(|p| p.children.iter().rev())); + } + // Subtree sizes: the next sibling follows a node's whole subtree. + let mut size = vec![1i64; n]; + for &i in order.iter().rev() { + let s: i64 = self.paths.get(i).map_or(0, |p| p.children.iter().filter_map(|c| size.get(*c)).sum()); + if let Some(x) = size.get_mut(i) { + *x += s; + } + } + let mut has_sibling = vec![false; n]; + for p in &self.paths { + for w in p.children.windows(2) { + if let Some(s) = w.first().and_then(|&c| has_sibling.get_mut(c)) { + *s = true; + } + } + } + let mut table = [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]; + for i in order { + let Some(p) = self.paths.get(i) else { continue }; + let jump = match (!p.children.is_empty(), has_sibling.get(i).copied().unwrap_or(false)) { + (true, true) => size.get(i).copied().unwrap_or(1), + (true, false) => -1, + (false, true) => 0, + (false, false) => -2, + }; + let token = i64::from(p.token); + table[0].push(i as i64); + table[1].push(if p.prop { -token } else { token }); + table[2].push(jump); + } + table + } + + fn section(&mut self, toc: &mut Vec<(&'static str, u64, u64)>, name: &'static str, start: u64) { + toc.push((name, start, self.offset() - start)); + } + + fn u64(&mut self, v: usize) { + self.out.extend_from_slice(&(v as u64).to_le_bytes()); + } + + fn sections(&mut self) -> Result<()> { + let mut toc = Vec::new(); + let start = self.offset(); + let mut raw = Vec::new(); + for t in &self.tokens { + raw.extend_from_slice(t.as_bytes()); + raw.push(0); + } + let comp = compress_block(&raw)?; + self.u64(self.tokens.len()); + self.u64(raw.len()); + self.u64(comp.len()); + self.out.extend_from_slice(&comp); + self.section(&mut toc, "TOKENS", start); + + let start = self.offset(); + let strings = std::mem::take(&mut self.strings); + self.u64(strings.len()); + self.u32s(strings.into_iter()); + self.section(&mut toc, "STRINGS", start); + + let start = self.offset(); + let fields = std::mem::take(&mut self.fields); + self.u64(fields.len()); + self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>())?; + let reps: Vec = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect(); + let comp = compress_block(&reps)?; + self.u64(comp.len()); + self.out.extend_from_slice(&comp); + self.section(&mut toc, "FIELDS", start); + + let start = self.offset(); + let sets = std::mem::take(&mut self.fieldsets); + self.u64(sets.len()); + self.ints(&sets)?; + self.section(&mut toc, "FIELDSETS", start); + + let start = self.offset(); + let table = self.path_table(); + self.u64(self.paths.len()); + self.u64(self.paths.len()); + for column in &table { + self.ints(column)?; + } + self.section(&mut toc, "PATHS", start); + + let start = self.offset(); + let specs = std::mem::take(&mut self.specs); + self.u64(specs.len()); + for k in 0..3 { + self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>())?; + } + self.section(&mut toc, "SPECS", start); + + let toc_at = self.offset(); + self.u64(toc.len()); + for (name, start, size) in toc { + let mut n = [0u8; 16]; + for (d, s) in n.iter_mut().zip(name.bytes()) { + *d = s; + } + self.out.extend_from_slice(&n); + self.out.extend_from_slice(&start.to_le_bytes()); + self.out.extend_from_slice(&size.to_le_bytes()); + } + if let Some(slot) = self.out.get_mut(16..24) { + slot.copy_from_slice(&toc_at.to_le_bytes()); + } + Ok(()) + } + + fn root_spec(&mut self, default_prim: &str, meters_per_unit: f64, up_axis: &str) -> Result<()> { + let fields = vec![ + ("defaultPrim", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(default_prim)))), + ("metersPerUnit", self.value(&UsdValue::Double(meters_per_unit))?), + ("upAxis", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(up_axis)))), + ("primChildren", self.token_vector(&[default_prim])), + ]; + self.spec(0, SPEC_PSEUDO_ROOT, fields); + Ok(()) + } + + fn finish(mut self) -> Result> { + self.sections()?; + Ok(self.out) + } +} + +/// Encode `layer` as a `.usdc` Crate binary. +pub fn usdc(layer: &UsdLayer) -> Result> { + let mut w = Writer::new(); + let root = &layer.root; + w.add_prim_paths(0, "/", root); + w.root_spec(&root.name, layer.meters_per_unit, &layer.up_axis)?; + w.prim_specs(&format!("/{}", root.name), root)?; + w.finish() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::{SPEC_ATTRIBUTE, SPEC_PRIM, Writer, rep, usda, usdc}; + use crate::codec::{self, ty}; + use crate::scene::{Specifier, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer}; + + impl Writer { + fn raw(&mut self, bytes: &[u8]) -> u64 { + let at = self.offset(); + self.out.extend_from_slice(bytes); + at + } + + fn prop_path(&mut self, parent: (usize, &str), name: &str) -> usize { + self.add_path(parent.0, parent.1, name, true).0 + } + } + + fn le(values: &[f64]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() + } + + #[test] + fn usda_and_usdc_round_trip_neutral_layer() { + let mut root = UsdPrim::new("World", "Xform"); + let mut mesh = UsdPrim::new("Tri", "Mesh"); + mesh.binding_api = true; + mesh.attrs = vec![ + UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(vec![0, 1, 2]))), + UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::rel("material:binding", "/World/Mat".into()), + ]; + root.children.push(mesh); + let mut mat = UsdPrim::new("Mat", "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", "/World/Mat/PBR.outputs:surface".into())); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs.push(UsdAttr::new("outputs:surface", "token", None)); + mat.children.push(pbr); + root.children.push(mat); + + let mut layer = UsdLayer::new(root); + layer.doc = Some("Test doc".into()); + layer.meters_per_unit = 0.01; + layer.up_axis = "Z".into(); + + let text = usda(&layer); + assert!(text.contains("doc = \"Test doc\"")); + assert!(text.contains("metersPerUnit = 0.01")); + assert!(text.contains("upAxis = \"Z\"")); + + for bytes in [text.as_bytes(), &usdc(&layer).unwrap()] { + let parsed = read_layer(bytes).unwrap(); + assert_eq!(parsed.meters_per_unit, Some(0.01)); + assert_eq!(parsed.up_axis.as_deref(), Some("Z")); + let tri = parsed.prims.iter().find(|p| p.path == "/World/Tri").unwrap(); + assert_eq!(tri.type_name, "Mesh"); + assert_eq!(tri.specifier, Specifier::Def); + assert_eq!(tri.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(tri.props.get("material:binding").and_then(|p| p.value.as_ref()), Some(&Val::Path(vec!["/World/Mat".into()]))); + } + } + + /// A Crate file assembled spec by spec with a class prim referenced by a def prim + /// (with customData on the reference), a time-sampled out-of-line double3 translate, + /// a token[] xformOpOrder, and an inlined diagonal matrix. + #[test] + fn crafted_crate_with_references_time_samples_and_inlined_values() { + let mut w = Writer::new(); + let (wp, wt) = w.add_path(0, "/", "W", false); + let (pp, pt) = w.add_path(0, "/", "P", false); + let (mp, mt) = w.add_path(pp, &pt, "M", false); + let ops = ["xformOp:translate", "xformOp:transform", "xformOpOrder"].map(|n| w.prop_path((wp, &wt), n)); + let attrs = ["points", "faceVertexCounts", "faceVertexIndices"].map(|n| w.prop_path((mp, &mt), n)); + w.root_spec("W", 1.0, "Y").unwrap(); + let empty = w.token(""); + let key = w.token("note"); + w.strings = vec![empty, key]; + let def = |t: &str, w: &mut Writer| { + vec![("specifier", rep(ty::SPECIFIER, codec::IS_INLINED, 0)), ("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(w.token(t))))] + }; + + // /W: def Xform (prepend references =

with customData = {note: 7}). + let mut fields = def("Xform", &mut w); + let mut r = vec![1u8 << 5]; + r.extend_from_slice(&1u64.to_le_bytes()); + r.extend_from_slice(&0u32.to_le_bytes()); + r.extend_from_slice(&(pp as u32).to_le_bytes()); + r.extend(le(&[0.0, 1.0])); + r.extend_from_slice(&1u64.to_le_bytes()); + r.extend_from_slice(&1u32.to_le_bytes()); + r.extend_from_slice(&8i64.to_le_bytes()); + r.extend_from_slice(&rep(ty::INT, codec::IS_INLINED, 7).to_le_bytes()); + fields.push(("references", rep(ty::REFERENCE_LIST_OP, 0, w.raw(&r)))); + w.spec(wp, SPEC_PRIM, fields); + + // translate.timeSamples = {0: (1, 0, 0), 10: (5, 0, 0)}, out-of-line double3 values. + let at = w.offset(); + let mut t = 32i64.to_le_bytes().to_vec(); + t.extend_from_slice(&2u64.to_le_bytes()); + t.extend(le(&[0.0, 10.0])); + t.extend_from_slice(&rep(ty::DOUBLE_VECTOR, 0, at + 8).to_le_bytes()); + let values_at = at + 40 + 8; + t.extend_from_slice(&56i64.to_le_bytes()); + t.extend(le(&[1.0, 0.0, 0.0, 5.0, 0.0, 0.0])); + t.extend_from_slice(&2u64.to_le_bytes()); + t.extend_from_slice(&rep(23, 0, values_at).to_le_bytes()); + t.extend_from_slice(&rep(23, 0, values_at + 24).to_le_bytes()); + let samples = rep(ty::TIME_SAMPLES, 0, w.raw(&t)); + let double3 = rep(ty::TOKEN, codec::IS_INLINED, u64::from(w.token("double3"))); + w.spec(ops[0], SPEC_ATTRIBUTE, vec![("typeName", double3), ("timeSamples", samples)]); + // transform: diag(2, 2, 2, 1), inlined. + w.spec(ops[1], SPEC_ATTRIBUTE, vec![("default", rep(ty::MATRIX4D, codec::IS_INLINED, 0x0102_0202))]); + let order: Vec = ["xformOp:translate", "xformOp:transform"].iter().map(|n| w.token(n)).collect(); + let mut o = 2u64.to_le_bytes().to_vec(); + o.extend(order.iter().flat_map(|t| t.to_le_bytes())); + let order = rep(ty::TOKEN, codec::IS_ARRAY, w.raw(&o)); + w.spec(ops[2], SPEC_ATTRIBUTE, vec![("default", order)]); + + // /P: class Xform holding def Mesh M. + let mut fields = def("Xform", &mut w); + fields[0].1 = rep(ty::SPECIFIER, codec::IS_INLINED, 2); + w.spec(pp, SPEC_PRIM, fields); + let fields = def("Mesh", &mut w); + w.spec(mp, SPEC_PRIM, fields); + let points = w.value(&UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])).unwrap(); + let counts = w.value(&UsdValue::Ints(vec![3])).unwrap(); + let indices = w.value(&UsdValue::Ints(vec![0, 1, 2])).unwrap(); + for (path, value) in attrs.into_iter().zip([points, counts, indices]) { + w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]); + } + let bytes = w.finish().unwrap(); + + let layer = read_layer(&bytes).unwrap(); + let w_prim = layer.prims.iter().find(|p| p.path == "/W").unwrap(); + assert_eq!(w_prim.references, vec!["/P"]); + assert_eq!(w_prim.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0, 0.0, 0.0]))); + assert_eq!( + w_prim.props.get("xformOp:transform").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0])) + ); + let p_prim = layer.prims.iter().find(|p| p.path == "/P").unwrap(); + assert_eq!(p_prim.specifier, Specifier::Class); + } +} diff --git a/crates/usd/tests/scene.rs b/crates/usd/tests/scene.rs new file mode 100644 index 000000000..d8fa22c7f --- /dev/null +++ b/crates/usd/tests/scene.rs @@ -0,0 +1,234 @@ +//! Known-answer USDA and USDC (Crate binary) corpus and round-trip integration tests. + +#![allow(clippy::unwrap_used)] + +use craft_usd::codec; +use craft_usd::scene::{ + Budget, MAX_DEPTH, SceneError, Specifier, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer, read_layer_with_budget, write_usda, write_usdc, +}; + +const CORPUS_USDA: &str = r#"#usda 1.0 +( + defaultPrim = "World" + doc = "Corpus test" + metersPerUnit = 0.01 + upAxis = "Z" + subLayers = [@./base.usda@] +) + +class Xform "Proto" +{ + def Mesh "Leaf" ( + prepend apiSchemas = ["MaterialBindingAPI"] + ) + { + int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + point3f[] points = [(0, 0, 0), (100, 0, 0), (0, 100, 0)] + normal3f[] normals = [(0, 0, 1), (0, 0, 1), (0, 0, 1)] ( + interpolation = "vertex" + ) + texCoord2f[] primvars:st = [(0, 0), (1, 0), (0, 1)] ( + interpolation = "vertex" + ) + rel material:binding = + } +} + +def Xform "World" +{ + double3 xformOp:translate = (0, 0, 100) + float3 xformOp:rotateXYZ = (0, 0, 90) + float3 xformOp:scale = (2, 2, 2) + uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] + + def Xform "Instance" ( + prepend references = + ) + { + matrix4d xformOp:transform = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (10, 0, 0, 1) ) + uniform token[] xformOpOrder = ["xformOp:transform"] + } + + over "Overlay" ( + active = false + ) + { + float3 xformOp:translate.timeSamples = { + 0: (1, 2, 3), + 10: (4, 5, 6), + } + } + + def Xform "External" ( + prepend references = @./other.usda@ + ) + { + variantSet "look" = { + "a" { + def Mesh "V" {} + } + } + } +} +"#; + +#[test] +fn usda_corpus_overlays_references_coordinates_transforms_and_meshes() { + let layer = read_layer(CORPUS_USDA.as_bytes()).unwrap(); + assert_eq!(layer.meters_per_unit, Some(0.01)); + assert_eq!(layer.up_axis.as_deref(), Some("Z")); + assert!(layer.warnings.iter().any(|w| w.contains("sublayers"))); + assert!(layer.warnings.iter().any(|w| w.contains("external references"))); + assert!(layer.warnings.iter().any(|w| w.contains("variant sets"))); + + let proto = layer.prims.iter().find(|p| p.path == "/Proto").unwrap(); + assert_eq!(proto.specifier, Specifier::Class); + assert_eq!(proto.type_name, "Xform"); + + let leaf = layer.prims.iter().find(|p| p.path == "/Proto/Leaf").unwrap(); + assert_eq!(leaf.specifier, Specifier::Def); + assert_eq!(leaf.type_name, "Mesh"); + assert_eq!(leaf.props.get("faceVertexCounts").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![3.0]))); + assert_eq!(leaf.props.get("faceVertexIndices").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 1.0, 2.0]))); + assert_eq!(leaf.props.get("points").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 100.0, 0.0]))); + assert_eq!(leaf.props.get("normals").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(leaf.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(leaf.props.get("material:binding").and_then(|p| p.value.as_ref()), Some(&Val::Path(vec!["/World/Materials/LeafMat".into()]))); + + let world = layer.prims.iter().find(|p| p.path == "/World").unwrap(); + assert_eq!(world.specifier, Specifier::Def); + assert_eq!(world.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 0.0, 100.0]))); + assert_eq!( + world.props.get("xformOpOrder").and_then(|p| p.value.as_ref()), + Some(&Val::Tok(vec!["xformOp:translate".into(), "xformOp:rotateXYZ".into(), "xformOp:scale".into()])) + ); + + let instance = layer.prims.iter().find(|p| p.path == "/World/Instance").unwrap(); + assert_eq!(instance.references, vec!["/Proto"]); + assert_eq!( + instance.props.get("xformOp:transform").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 10.0, 0.0, 0.0, 1.0])) + ); + + let overlay = layer.prims.iter().find(|p| p.path == "/World/Overlay").unwrap(); + assert_eq!(overlay.specifier, Specifier::Over); + assert_eq!(overlay.active, Some(false)); + assert_eq!(overlay.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0, 2.0, 3.0]))); +} + +fn sample_scene_layer() -> UsdLayer { + let mut root = UsdPrim::new("Scene", "Xform"); + let mut mesh = UsdPrim::new("QuadMesh", "Mesh"); + mesh.binding_api = true; + mesh.attrs = vec![ + UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]))), + UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3, 3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(vec![0, 1, 2, 0, 2, 3]))), + UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(), + UsdAttr::rel("material:binding", "/Scene/Materials/Default".into()), + ]; + + let mut subset = UsdPrim::new("Sub0", "GeomSubset"); + subset.binding_api = true; + subset.attrs = vec![ + UsdAttr::new("elementType", "token", Some(UsdValue::Token("face".into()))).uniform(), + UsdAttr::new("familyName", "token", Some(UsdValue::Token("materialBind".into()))).uniform(), + UsdAttr::new("indices", "int[]", Some(UsdValue::Ints(vec![1]))), + UsdAttr::rel("material:binding", "/Scene/Materials/Accent".into()), + ]; + mesh.children.push(subset); + root.children.push(mesh); + + let mut materials = UsdPrim::new("Materials", "Scope"); + for mat_name in ["Default", "Accent"] { + let mut mat = UsdPrim::new(mat_name, "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", format!("/Scene/Materials/{mat_name}/PBR.outputs:surface"))); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs = vec![ + UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPreviewSurface".into()))).uniform(), + UsdAttr::new("inputs:useSpecularWorkflow", "int", Some(UsdValue::Int(0))), + UsdAttr::new("inputs:scale", "float4", Some(UsdValue::Float4([2.0, 2.0, 2.0, 1.0]))), + UsdAttr::new("inputs:file", "asset", Some(UsdValue::Asset("./tex.png".into()))), + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), + UsdAttr::new("outputs:surface", "token", None), + ]; + mat.children.push(pbr); + materials.children.push(mat); + } + root.children.push(materials); + + let mut layer = UsdLayer::new(root); + layer.doc = Some("Integration round-trip".into()); + layer.meters_per_unit = 0.01; + layer.up_axis = "Z".into(); + layer +} + +#[test] +fn usda_and_usdc_round_trip_known_answers() { + let scene = sample_scene_layer(); + let text = write_usda(&scene); + assert!(text.starts_with("#usda 1.0")); + assert!(text.contains("defaultPrim = \"Scene\"")); + assert!(text.contains("doc = \"Integration round-trip\"")); + assert!(text.contains("metersPerUnit = 0.01")); + assert!(text.contains("upAxis = \"Z\"")); + + let crate_bytes = write_usdc(&scene).unwrap(); + assert!(crate_bytes.starts_with(codec::MAGIC)); + assert_eq!(&crate_bytes[8..11], &[0, 8, 0]); + + for (label, bytes) in [("usda", text.as_bytes()), ("usdc", crate_bytes.as_slice())] { + let parsed = read_layer(bytes).unwrap(); + assert_eq!(parsed.meters_per_unit, Some(0.01), "{label}"); + assert_eq!(parsed.up_axis.as_deref(), Some("Z"), "{label}"); + + let mesh = parsed.prims.iter().find(|p| p.path == "/Scene/QuadMesh").unwrap(); + assert_eq!(mesh.type_name, "Mesh", "{label}"); + assert_eq!(mesh.specifier, Specifier::Def, "{label}"); + assert_eq!(mesh.props.get("faceVertexCounts").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![3.0, 3.0])), "{label}"); + assert_eq!( + mesh.props.get("faceVertexIndices").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0])), + "{label}" + ); + assert_eq!(mesh.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex"), "{label}"); + assert_eq!( + mesh.props.get("material:binding").and_then(|p| p.value.as_ref()), + Some(&Val::Path(vec!["/Scene/Materials/Default".into()])), + "{label}" + ); + + let subset = parsed.prims.iter().find(|p| p.path == "/Scene/QuadMesh/Sub0").unwrap(); + assert_eq!(subset.type_name, "GeomSubset", "{label}"); + assert_eq!(subset.props.get("indices").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0])), "{label}"); + + let pbr = parsed.prims.iter().find(|p| p.path == "/Scene/Materials/Default/PBR").unwrap(); + assert_eq!(pbr.props.get("info:id").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["UsdPreviewSurface".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:file").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["./tex.png".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:varname").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["st".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:scale").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![2.0, 2.0, 2.0, 1.0])), "{label}"); + } +} + +#[test] +fn decoded_budget_and_invalid_inputs_are_enforced() { + let scene = sample_scene_layer(); + let crate_bytes = write_usdc(&scene).unwrap(); + let mut tiny_budget = Budget::with_limit(64); + assert!(matches!(read_layer_with_budget(&crate_bytes, &mut tiny_budget), Err(SceneError::TooLarge(_)))); + + assert!(matches!(read_layer(b"not a usd file"), Err(SceneError::Malformed(_)))); + assert!(matches!(read_layer(b"PXR-USDC\x00\x03\x00\x00"), Err(SceneError::Unsupported(_)))); + + let mut bad_target = UsdLayer::new(UsdPrim::new("Root", "Xform")); + bad_target.root.attrs.push(UsdAttr::rel("material:binding", "/Does/Not/Exist".into())); + assert!(matches!(write_usdc(&bad_target), Err(SceneError::Invalid(_)))); + assert_eq!(MAX_DEPTH, 128); +} diff --git a/crates/video/src/av1/decode/decoder.rs b/crates/video/src/av1/decode/decoder.rs index 4a922cce1..1aa8d9261 100644 --- a/crates/video/src/av1/decode/decoder.rs +++ b/crates/video/src/av1/decode/decoder.rs @@ -604,6 +604,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + pub fn stats(&self) -> DecodeStats { self.stats.lock().map(|s| *s).unwrap_or_default() } diff --git a/crates/video/src/hevc/decode/decoder.rs b/crates/video/src/hevc/decode/decoder.rs index 2f226d571..66c3ac77f 100644 --- a/crates/video/src/hevc/decode/decoder.rs +++ b/crates/video/src/hevc/decode/decoder.rs @@ -296,6 +296,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + pub fn take_error(&mut self) -> Option { self.shared.error.lock().ok().and_then(|mut e| e.take()) } diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 81a4e5b0e..d3267c7ba 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -66,7 +66,7 @@ mod track; feature = "ffv1", feature = "vp8-decode" ))] -pub use track::TrackDecoder; +pub use track::{TrackDecoder, TrackDecoderOptions}; #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] pub mod apv; diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs index d89eeaeac..fa7be7e51 100644 --- a/crates/video/src/track.rs +++ b/crates/video/src/track.rs @@ -92,16 +92,33 @@ enum Inner { /// } /// # Ok(()) } /// ``` +/// Options for [`TrackDecoder::with_options`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TrackDecoderOptions { + /// Worker threads for codecs that decode in parallel (`None` uses the codec default; + /// `Some(1)` decodes on the calling thread). Values of `0` are clamped to `1`. + pub threads: Option, + /// Draft mode (approximate, for reduced-resolution playback only; never for export). + pub draft: bool, +} + pub struct TrackDecoder { inner: Inner, codec: CodecId, + threads: Option, + draft: bool, /// Frames finished by a call that then failed, which the next call returns first. held: Vec, } impl std::fmt::Debug for TrackDecoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive() + f.debug_struct("TrackDecoder") + .field("codec", &self.codec) + .field("threads", &self.threads) + .field("draft", &self.draft) + .field("held", &self.held.len()) + .finish_non_exhaustive() } } @@ -114,7 +131,20 @@ impl TrackDecoder { /// allowed, is [`VideoError::Malformed`]. Unsupported codec features are /// [`VideoError::Unsupported`]. pub fn new(params: &CodecParams) -> Result { - Ok(TrackDecoder { inner: Inner::new(params)?, codec: params.codec, held: Vec::new() }) + Self::with_options(params, TrackDecoderOptions::default()) + } + + /// Like [`TrackDecoder::new`], capped at `threads` worker threads (`1` decodes on the calling + /// thread; `0` is clamped to `1`) for codecs that decode in parallel. + pub fn with_threads(params: &CodecParams, threads: usize) -> Result { + Self::with_options(params, TrackDecoderOptions { threads: Some(threads), draft: false }) + } + + /// Like [`TrackDecoder::new`], with explicit threading and draft options. + pub fn with_options(params: &CodecParams, options: TrackDecoderOptions) -> Result { + let threads = options.threads.map(|t| t.max(1)); + let normalized = TrackDecoderOptions { threads, draft: options.draft }; + Ok(TrackDecoder { inner: Inner::new(params, normalized)?, codec: params.codec, threads, draft: options.draft, held: Vec::new() }) } /// The track's codec, as `params` gave it. @@ -122,6 +152,44 @@ impl TrackDecoder { self.codec } + /// The explicit worker-thread cap, or `None` when using the codec's default. + pub fn threads(&self) -> Option { + self.threads + } + + /// Whether draft mode is enabled (for reduced-resolution playback only; never for export). + pub fn draft(&self) -> bool { + self.draft + } + + /// Toggle draft mode (skipping non-reference loop/deblocking filters on codecs that support + /// it). Approximate, for reduced-resolution playback only; never use for export. + pub fn set_draft(&mut self, on: bool) { + self.draft = on; + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => dec.set_draft(on), + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => dec.set_draft(on), + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => dec.set_draft(on), + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => dec.set_draft(on), + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(_) => {} + #[cfg(feature = "prores")] + Inner::ProRes => {} + #[cfg(feature = "dnx")] + Inner::Dnx => {} + #[cfg(feature = "apv-decode")] + Inner::Apv => {} + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => {} + #[cfg(feature = "vp8-decode")] + Inner::Vp8(_) => {} + } + } + /// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with /// its presentation timestamp. Returns the frames that became ready for display, in display /// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a @@ -247,7 +315,8 @@ impl TrackDecoder { #[cfg(feature = "hevc-decode")] Inner::Hevc { dec, config } => { // The HEVC decoder has no reset of its own: a new one starts from nothing. - let mut fresh = Box::new(hevc::decode::Decoder::new()); + let mut fresh = Box::new(self.threads.map_or_else(hevc::decode::Decoder::new, hevc::decode::Decoder::with_threads)); + fresh.set_draft(self.draft); configure_hevc(&mut fresh, config)?; *dec = fresh; Ok(()) @@ -260,7 +329,8 @@ impl TrackDecoder { #[cfg(feature = "av1-decode")] Inner::Av1 { dec, config_obus } => { // The AV1 decoder has no reset of its own: a new one starts from nothing. - let mut fresh = Box::new(av1::decode::Decoder::new()); + let mut fresh = Box::new(self.threads.map_or_else(av1::decode::Decoder::new, av1::decode::Decoder::with_threads)); + fresh.set_draft(self.draft); configure_av1(&mut fresh, config_obus)?; *dec = fresh; Ok(()) @@ -335,35 +405,45 @@ impl TrackDecoder { } impl Inner { - fn new(params: &CodecParams) -> Result { + fn new(params: &CodecParams, options: TrackDecoderOptions) -> Result { let codec = params.codec; let extradata = ¶ms.extradata; - let _ = extradata; + let _ = (extradata, options); match codec { #[cfg(feature = "h264-decode")] CodecId::H264 => { - let mut dec = Box::new(h264::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(h264::decode::Decoder::new, h264::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_h264(&mut dec, extradata)?; Ok(Inner::H264 { dec, config: extradata.to_vec() }) } #[cfg(feature = "hevc-decode")] CodecId::Hevc => { - let mut dec = Box::new(hevc::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(hevc::decode::Decoder::new, hevc::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_hevc(&mut dec, extradata)?; Ok(Inner::Hevc { dec, config: extradata.to_vec() }) } #[cfg(feature = "vp9-decode")] - CodecId::Vp9 => Ok(Inner::Vp9(Box::default())), + CodecId::Vp9 => { + let mut dec = Box::new(options.threads.map_or_else(vp9::decode::Decoder::new, vp9::decode::Decoder::with_threads)); + dec.set_draft(options.draft); + Ok(Inner::Vp9(dec)) + } #[cfg(feature = "av1-decode")] CodecId::Av1 => { let config_obus = av1c_config_obus(extradata)?.to_vec(); - let mut dec = Box::new(av1::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(av1::decode::Decoder::new, av1::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_av1(&mut dec, &config_obus)?; Ok(Inner::Av1 { dec, config_obus }) } #[cfg(feature = "mpeg2-decode")] CodecId::Mpeg2Video => { let mut dec = Box::new(mpeg2::Decoder::new()); + if let Some(threads) = options.threads { + dec.set_threads(threads > 1); + } if !extradata.is_empty() { check_mpeg2_config(extradata)?; dec.decode(extradata, 0)?; diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs index 42d3ab861..d9da7fe72 100644 --- a/crates/video/src/track/tests.rs +++ b/crates/video/src/track/tests.rs @@ -389,3 +389,85 @@ fn new_codec_errors_keep_their_category() { #[cfg(feature = "vp8-decode")] assert!(matches!(VideoError::from(crate::vp8::Error::Invalid("header".into())), VideoError::Malformed(_))); } + +#[test] +#[allow(irrefutable_let_patterns, clippy::cognitive_complexity)] +fn track_decoder_options_and_draft_persist_across_reset() { + #[allow(unused_variables)] + let opts = TrackDecoderOptions { threads: Some(0), draft: true }; + #[cfg(feature = "h264-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::H264, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } else { + panic!("expected H264 inner"); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + dec.set_draft(false); + assert!(!dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert!(!inner.draft()); + } + let dec2 = TrackDecoder::with_threads(¶ms(CodecId::H264, &[]), 2).unwrap(); + assert_eq!(dec2.threads(), Some(2)); + assert!(!dec2.draft()); + if let Inner::H264 { dec: inner, .. } = &dec2.inner { + let expected = if cfg!(all(feature = "threads", not(target_arch = "wasm32"))) { 2 } else { 1 }; + assert_eq!(inner.threads(), expected); + assert!(!inner.draft()); + } + } + #[cfg(feature = "hevc-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Hevc, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Hevc { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Hevc { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + } + #[cfg(feature = "av1-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Av1, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Av1 { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Av1 { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + } + #[cfg(feature = "vp9-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Vp9, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Vp9(inner) = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Vp9(inner) = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + } +} diff --git a/crates/video/src/vp9/decode/decoder.rs b/crates/video/src/vp9/decode/decoder.rs index c6a3fe4bd..23016b2fe 100644 --- a/crates/video/src/vp9/decode/decoder.rs +++ b/crates/video/src/vp9/decode/decoder.rs @@ -164,6 +164,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + /// Decode one chunk (a frame or a superframe, as stored in one IVF / WebM / MP4 sample). /// Returns the pictures finished so far, in order; each carries the `pts` of the chunk that /// showed it. With frame threads a picture may come out of a later call or [`Self::flush`]. diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml index 9b1304d89..1807a96f9 100644 --- a/crates/xfdf/Cargo.toml +++ b/crates/xfdf/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-xfdf" -description = "Bounded XFDF field-value reader without PDF or form policy" +description = "Bounded XFDF field-value reader and annotation/FDF grammar without PDF or form policy" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/xfdf/src/grammar.rs b/crates/xfdf/src/grammar.rs new file mode 100644 index 000000000..d757e8558 --- /dev/null +++ b/crates/xfdf/src/grammar.rs @@ -0,0 +1,443 @@ +//! Portable XFDF annotation and FDF grammar (no PDF COS document or annotation models). + +use std::fmt::Write as _; + +use craft_xml::esc_attr as esc; + +use crate::{check_form_xml_depth, el_text, parse_form_xml, xml_nesting_depth}; + +/// XFDF's own namespace (ISO 19444-1). +pub const XFDF_NS: &str = "http://ns.adobe.com/xfdf/"; + +/// Rich text deeper than this is written as text rather than as markup, so the XFDF it goes into +/// stays well inside the nesting the reader accepts (`MAX_XML_DEPTH`). +const MAX_RICH_DEPTH: usize = 512; + +/// PDF annotation `/Subtype` names paired with their XFDF element names. +pub const SUBTYPES: [(&str, &str); 17] = [ + ("Text", "text"), + ("FreeText", "freetext"), + ("Line", "line"), + ("Square", "square"), + ("Circle", "circle"), + ("Polygon", "polygon"), + ("PolyLine", "polyline"), + ("Highlight", "highlight"), + ("Underline", "underline"), + ("Squiggly", "squiggly"), + ("StrikeOut", "strikeout"), + ("Stamp", "stamp"), + ("Caret", "caret"), + ("Ink", "ink"), + ("FileAttachment", "fileattachment"), + ("Sound", "sound"), + ("Redact", "redact"), +]; + +/// PDF annotation `/F` bitflags paired with their XFDF `flags` attribute tokens. +pub const FLAGS: [(i64, &str); 9] = [ + (1, "invisible"), + (2, "hidden"), + (4, "print"), + (8, "nozoom"), + (16, "norotate"), + (32, "noview"), + (64, "readonly"), + (128, "locked"), + (256, "togglenoview"), +]; + +/// PDF annotation border style (`/BS /S`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BorderStyle { + Solid, + Dash, + Bevelled, + Inset, + Underline, +} + +impl BorderStyle { + /// Return the PDF `/BS /S` name for this border style. + pub fn as_pdf_name(self) -> &'static str { + match self { + Self::Solid => "S", + Self::Dash => "D", + Self::Bevelled => "B", + Self::Inset => "I", + Self::Underline => "U", + } + } + + fn as_xfdf_attr(self) -> Option<&'static str> { + match self { + Self::Dash => Some("dash"), + Self::Bevelled => Some("bevelled"), + Self::Inset => Some("inset"), + Self::Underline => Some("underline"), + Self::Solid => None, + } + } +} + +/// PDF Caret annotation `/Sy` symbol. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CaretSymbol { + Paragraph, + None, +} + +impl CaretSymbol { + /// Return the PDF `/Sy` name for this caret symbol. + pub fn as_pdf_name(self) -> &'static str { + match self { + Self::Paragraph => "P", + Self::None => "None", + } + } +} + +/// Portable XFDF 3.0 annotation formatting attributes. +#[derive(Default, Debug, PartialEq)] +pub struct AnnotFormat { + pub width: Option, + pub border_style: Option, + pub dashes: Option>, + pub cloudy_intensity: Option>, + pub rotation: Option, + pub justification: Option, + pub fringe: Option<[f64; 4]>, + pub leader_length: Option, + pub leader_extend: Option, + pub leader_offset: Option, + pub caption: Option, + pub caption_style: Option, + pub caption_offset: Option<[f64; 2]>, + pub symbol: Option, + pub overlay_text: Option, + pub overlay_text_repeat: Option, +} + +fn format_num(v: f64) -> String { + let s = format!("{v:.4}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +fn parse_csv(list: &str) -> Vec { + let v: Vec = list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect(); + if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() } +} + +fn hex_color(c: &[f64]) -> Option { + let rgb = match c.len() { + 1 => [c[0]; 3], + 3 => [c[0], c[1], c[2]], + 4 => [(1.0 - c[0]) * (1.0 - c[3]), (1.0 - c[1]) * (1.0 - c[3]), (1.0 - c[2]) * (1.0 - c[3])], + _ => return None, + }; + Some(format!( + "#{:02X}{:02X}{:02X}", + (rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8, + (rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8, + (rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8 + )) +} + +/// Format XFDF 3.0 annotation formatting attributes into `attrs`. +pub fn write_format_attrs(fmt: &AnnotFormat, is_free_text: bool, attrs: &mut String) { + let list = |v: &[f64]| v.iter().map(|x| format_num(*x)).collect::>().join(","); + if let Some(w) = fmt.width.filter(|w| w.is_finite()) { + let _ = write!(attrs, " width=\"{}\"", format_num(w)); + } + if let Some(intensity) = fmt.cloudy_intensity { + attrs.push_str(" style=\"cloudy\""); + if let Some(i) = intensity.filter(|i| i.is_finite()) { + let _ = write!(attrs, " intensity=\"{}\"", format_num(i)); + } + } else if let Some(s) = fmt.border_style.and_then(BorderStyle::as_xfdf_attr) { + let _ = write!(attrs, " style=\"{s}\""); + } + if let Some(dashes) = &fmt.dashes + && !dashes.is_empty() + && dashes.iter().all(|v| v.is_finite()) + { + let _ = write!(attrs, " dashes=\"{}\"", list(dashes)); + } + if let Some(r) = fmt.rotation { + let _ = write!(attrs, " rotation=\"{r}\""); + } + if let Some(q) = fmt.justification { + match (is_free_text, q) { + (true, 0) => attrs.push_str(" justification=\"left\""), + (true, 1) => attrs.push_str(" justification=\"centered\""), + (true, 2) => attrs.push_str(" justification=\"right\""), + (true, _) => {} + (false, q) => { + let _ = write!(attrs, " justification=\"{q}\""); + } + } + } + if let Some(rd) = fmt.fringe + && rd.iter().all(|v| v.is_finite()) + { + let _ = write!(attrs, " fringe=\"{}\"", list(&rd)); + } + if let Some(ll) = fmt.leader_length.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leaderLength=\"{}\"", format_num(ll)); + } + if let Some(lle) = fmt.leader_extend.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leaderExtend=\"{}\"", format_num(lle)); + } + if let Some(llo) = fmt.leader_offset.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leader-offset=\"{}\"", format_num(llo)); + } + if let Some(cap) = fmt.caption { + let _ = write!(attrs, " caption=\"{}\"", if cap { "yes" } else { "no" }); + } + if let Some(cp) = &fmt.caption_style { + let _ = write!(attrs, " caption-style=\"{}\"", esc(cp)); + } + if let Some([h, v]) = fmt.caption_offset + && h.is_finite() + && v.is_finite() + { + let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", format_num(h), format_num(v)); + } + match fmt.symbol { + Some(CaretSymbol::Paragraph) => attrs.push_str(" symbol=\"paragraph\""), + Some(CaretSymbol::None) => attrs.push_str(" symbol=\"none\""), + None => {} + } + if let Some(t) = &fmt.overlay_text { + let _ = write!(attrs, " overlay-text=\"{}\"", esc(t)); + } + if let Some(repeat) = fmt.overlay_text_repeat { + let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\""); + } +} + +/// Parse XFDF 3.0 annotation formatting attributes from an XML element. +pub fn parse_format_attrs(node: &craft_xml::El) -> AnnotFormat { + let num = |a: &str| node.attr(a).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); + let style = node.attr("style").map(str::trim); + let dashes = node.attr("dashes").map(parse_csv).filter(|v| !v.is_empty() && v.iter().all(|x| *x >= 0.0) && v.iter().any(|x| *x > 0.0)); + let border_style = match style { + Some("dash") => Some(BorderStyle::Dash), + Some("bevelled" | "beveled") => Some(BorderStyle::Bevelled), + Some("inset") => Some(BorderStyle::Inset), + Some("underline") => Some(BorderStyle::Underline), + Some("solid") => Some(BorderStyle::Solid), + _ => None, + }; + let cloudy_intensity = (style == Some("cloudy")).then(|| Some(num("intensity").unwrap_or(1.0).clamp(0.0, 2.0))); + let (h, v) = (num("caption-offset-h"), num("caption-offset-v")); + AnnotFormat { + width: num("width"), + border_style, + dashes, + cloudy_intensity, + rotation: node.attr("rotation").and_then(|r| r.trim().parse::().ok()).map(i64::from), + justification: match node.attr("justification").map(str::trim) { + Some("left" | "0") => Some(0), + Some("centered" | "center" | "1") => Some(1), + Some("right" | "2") => Some(2), + _ => None, + }, + fringe: node.attr("fringe").map(parse_csv).and_then(|r| r.try_into().ok()), + leader_length: num("leaderLength"), + leader_extend: num("leaderExtend").filter(|v| *v >= 0.0), + leader_offset: num("leader-offset").filter(|v| *v >= 0.0), + caption: match node.attr("caption").map(str::trim) { + Some("yes" | "true") => Some(true), + Some("no" | "false") => Some(false), + _ => None, + }, + caption_style: node.attr("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")).map(str::to_owned), + caption_offset: (h.is_some() || v.is_some()).then(|| [h.unwrap_or(0.0), v.unwrap_or(0.0)]), + symbol: match node.attr("symbol").map(str::trim) { + Some("paragraph" | "P") => Some(CaretSymbol::Paragraph), + Some("none" | "None") => Some(CaretSymbol::None), + _ => None, + }, + overlay_text: node.attr("overlay-text").map(str::to_owned), + overlay_text_repeat: match node.attr("overlay-text-repeat").map(str::trim) { + Some("true" | "yes") => Some(true), + Some("false" | "no") => Some(false), + _ => None, + }, + } +} + +/// Format PDF `/F` annotation bitflags as a comma-separated XFDF `flags` string. +pub fn format_flags(flags: i64) -> String { + FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect::>().join(",") +} + +/// Parse an XFDF `flags` attribute into PDF `/F` annotation bitflags. +pub fn parse_flags(attr: Option<&str>) -> i64 { + attr.unwrap_or("print") + .split(',') + .filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0)) + .fold(0, |bits, flag| bits | flag) +} + +/// Pairs `x,y;x,y;…` (XFDF vertices and ink gestures). +pub fn pairs(text: &str) -> Vec<[f64; 2]> { + text.split(';').filter_map(|p| if let [x, y] = parse_csv(p).as_slice() { Some([*x, *y]) } else { None }).collect() +} + +/// Format coordinate pairs as `x,y;x,y;…`. +pub fn format_pairs(pts: &[[f64; 2]]) -> String { + pts.iter().map(|p| format!("{},{}", format_num(p[0]), format_num(p[1]))).collect::>().join(";") +} + +/// Rich text (`/RC`) as `` holds it: its root element alone (no XML +/// declaration), when the text is well-formed XML; `None` otherwise. +pub fn rich_text_element(rc: &str) -> Option { + let t = rc.trim_start_matches('\u{feff}'); + if xml_nesting_depth(t) > MAX_RICH_DEPTH { + return None; + } + let parsed = parse_form_xml(t).ok()?; + Some(parsed.to_xml()) +} + +/// Recursively extract plain text from a `` element, a `\r`-separated line +/// per paragraph or `
` (what `/Contents` gets when `` comes without +/// ``). Unlike [`direct_text`], this walks descendant elements. +pub fn rich_plain(node: &craft_xml::El) -> String { + fn walk(node: &craft_xml::El, out: &mut String) { + for n in &node.children { + match n { + craft_xml::Node::El(el) => { + if el.local() == "br" || (matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r')) { + out.push('\r'); + } + walk(el, out); + } + craft_xml::Node::Text(t) if !(t.trim().is_empty() && t.contains('\n')) => { + out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r")); + } + _ => {} + } + } + } + let mut out = String::new(); + walk(node, &mut out); + out.trim_end_matches('\r').to_string() +} + +/// The one element `markup` (cut out of `rich`, a ``) as an XML +/// document of its own: the namespaces it inherits from the XFDF around it are declared on it. +pub fn standalone(el: &craft_xml::El, ns: &[(String, String)]) -> String { + let mut clone = (*el).clone(); + let markup = clone.to_xml(); + if let Some((_, uri)) = ns.iter().rfind(|(p, _)| p.is_empty()) + && !uri.is_empty() + && uri != XFDF_NS + && !clone.has_attr("xmlns") + { + clone.set_attr("xmlns", uri); + } + for (prefix, uri) in ns { + if prefix.is_empty() || prefix == "xml" { + continue; + } + let attr_name = format!("xmlns:{prefix}"); + if markup.contains(&format!("{prefix}:")) && !clone.has_attr(&attr_name) { + clone.set_attr(&attr_name, uri); + } + } + clone.to_xml() +} + +/// Whether `text` is XFDF with comments in it (what a paste of copied comments carries). +pub fn is_xfdf_comments(text: &str) -> bool { + let head: String = text.chars().take(400).collect(); + head.contains(" bool { + matches!(key, b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key == b"AP" && !is_stamp) +} + +/// Format a colour attribute (` name="#RRGGBB"`) when `color` is 1, 3, or 4 components. +pub fn format_color_attr(name: &str, color: &[f64], out: &mut String) { + if let Some(c) = hex_color(color) { + let _ = write!(out, " {name}=\"{c}\""); + } +} + +/// Concatenate only the direct text children of `node`, without recursing into child elements +/// (unlike [`rich_plain`]). +pub fn direct_text(node: &craft_xml::El) -> String { + el_text(node) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_attrs_round_trip() { + let fmt = AnnotFormat { + width: Some(2.5), + border_style: Some(BorderStyle::Dash), + dashes: Some(vec![3.0, 1.5]), + rotation: Some(90), + justification: Some(1), + caption: Some(true), + symbol: Some(CaretSymbol::Paragraph), + overlay_text: Some("REDACT".into()), + overlay_text_repeat: Some(true), + ..AnnotFormat::default() + }; + let mut attrs = String::new(); + write_format_attrs(&fmt, true, &mut attrs); + let xml = format!(""); + let parsed_xml = parse_form_xml(&xml); + assert!(parsed_xml.is_ok(), "failed to parse generated attributes: {xml}"); + if let Ok(el) = parsed_xml { + let parsed = parse_format_attrs(&el); + assert_eq!(parsed.width, Some(2.5)); + assert_eq!(parsed.border_style, Some(BorderStyle::Dash)); + assert_eq!(parsed.dashes.as_deref(), Some(&[3.0, 1.5][..])); + assert_eq!(parsed.rotation, Some(90)); + assert_eq!(parsed.justification, Some(1)); + assert_eq!(parsed.caption, Some(true)); + assert_eq!(parsed.symbol, Some(CaretSymbol::Paragraph)); + assert_eq!(parsed.overlay_text.as_deref(), Some("REDACT")); + assert_eq!(parsed.overlay_text_repeat, Some(true)); + } + } + + #[test] + fn flags_and_pairs_and_fdf_skip_keys() { + assert_eq!(format_flags(parse_flags(Some("print,locked"))), "print,locked"); + assert_eq!(pairs("1,2;3.5,4"), vec![[1.0, 2.0], [3.5, 4.0]]); + assert_eq!(format_pairs(&[[1.0, 2.0], [3.5, 4.0]]), "1,2;3.5,4"); + assert!(fdf_annot_skip_key(b"AP", false)); + assert!(!fdf_annot_skip_key(b"AP", true)); + assert!(fdf_annot_skip_key(b"Popup", true)); + assert!(is_xfdf_comments("")); + } +} diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index 002376106..31188fd46 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -1,6 +1,9 @@ -//! Bounded XFDF field values; PDF annotations and form application remain caller-owned. +//! Bounded XFDF field values and annotation/FDF grammar; PDF annotations and form application remain caller-owned. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] + +pub mod grammar; +pub use grammar::is_xfdf_comments; const MAX_NODES: u32 = 2_000_000; const MAX_DEPTH: usize = 64; const MAX_XML_DEPTH: usize = 1024; diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index a75874e71..44b0fbf22 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -291,8 +291,16 @@ impl<'a> Package<'a> { if rows.dropped > 0 { self.warn(format!("sheet \"{}\": {} cells or rows outside the 1,048,576 × 16,384 grid were dropped", entry.name, rows.dropped)); } - let mut sheet = - SheetPart { part, root: root.unwrap_or_default(), rels, rows: rows.rows, dropped: rows.dropped, damaged, ..SheetPart::default() }; + let mut sheet = SheetPart { + part, + root: root.unwrap_or_default(), + rels, + rows: rows.rows, + dropped: rows.dropped, + dropped_cells: rows.dropped_cells, + damaged, + ..SheetPart::default() + }; sheet.lift(); Ok(sheet) } diff --git a/crates/xlsx/src/sheet.rs b/crates/xlsx/src/sheet.rs index 2691764d5..16026c6a0 100644 --- a/crates/xlsx/src/sheet.rs +++ b/crates/xlsx/src/sheet.rs @@ -190,6 +190,8 @@ pub struct SheetPart { pub rows: u64, /// Rows and cells dropped because their position was outside the grid or unreadable. pub dropped: u64, + /// Cell elements (``) inside dropped rows or dropped for an invalid/out-of-grid reference. + pub dropped_cells: u64, /// Why reading stopped early, when the part is damaged; the rows before the damage were /// handed out. pub damaged: Option, @@ -361,6 +363,7 @@ pub(crate) struct RowReader { next_row: u32, pub(crate) rows: u64, pub(crate) dropped: u64, + pub(crate) dropped_cells: u64, } impl RowReader { @@ -371,11 +374,13 @@ impl RowReader { Some(r) if (1..=MAX_ROWS).contains(&r) => r - 1, Some(_) => { self.dropped += 1; + self.dropped_cells += e.children("c").count() as u64; return None; } None if self.next_row < MAX_ROWS => self.next_row, None => { self.dropped += 1; + self.dropped_cells += e.children("c").count() as u64; return None; } }; @@ -398,12 +403,14 @@ impl RowReader { Some(p) => p, None => { self.dropped += 1; + self.dropped_cells += 1; continue; } }, None if next_col < MAX_COLS => CellRef::new(index, next_col), None => { self.dropped += 1; + self.dropped_cells += 1; continue; } }; @@ -569,7 +576,20 @@ mod tests { assert_eq!(next, Some(3)); assert!(r.row(&craft_xml::El::new("row").with_attr("r", "1048577")).is_none()); assert!(r.row(&craft_xml::El::new("row").with_attr("r", "0")).is_none()); - assert_eq!((r.rows, r.dropped), (4, 3)); + assert_eq!((r.rows, r.dropped, r.dropped_cells), (4, 3, 1)); + } + + #[test] + fn dropped_cells_counts_cells_in_dropped_rows_and_bad_refs() { + let mut r = RowReader::default(); + let bad_row_zero = craft_xml::Options::local().parse(br#"12"#).unwrap(); + let bad_row_high = craft_xml::Options::local().parse(br#"3"#).unwrap(); + let bad_cell = craft_xml::Options::local().parse(br#"45"#).unwrap(); + assert!(r.row(&bad_row_zero).is_none()); + assert!(r.row(&bad_row_high).is_none()); + let kept = r.row(&bad_cell).unwrap(); + assert_eq!(kept.cells.len(), 1); + assert_eq!((r.dropped, r.dropped_cells), (3, 4)); } #[test] diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index b9b3b3d80..0f26267c1 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -108,6 +108,15 @@ impl<'a> Archive<'a> { Ok(Some(file.is_dir())) } + /// Whether the entry at `index` is a symbolic link according to its Unix mode bits. + pub fn entry_is_symlink(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(file.unix_mode().is_some_and(|mode| mode & 0o170000 == 0o120000))) + } + /// Declared decoded and compressed sizes at `index`, without name lookup. pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { @@ -274,4 +283,30 @@ mod ownership_tests { drop(clone); assert!(weak.upgrade().is_none()); } + + #[test] + fn entry_is_symlink_reports_unix_symlink_entries() { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.add_symlink("link", "/outside", zip::write::SimpleFileOptions::default()).unwrap(); + zip.start_file("file.txt", zip::write::SimpleFileOptions::default()).unwrap(); + std::io::Write::write_all(&mut zip, b"ok").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 4, max_total_bytes: 16 }).unwrap(); + assert_eq!(archive.entry_is_symlink(0).unwrap(), Some(true)); + assert_eq!(archive.entry_is_symlink(1).unwrap(), Some(false)); + assert_eq!(archive.entry_is_symlink(2).unwrap(), None); + } + + #[test] + fn streaming_writer_supports_directories_and_custom_destinations() { + let mut writer = crate::Writer::to_writer(Cursor::new(Vec::new())); + writer.add_directory("resources/").unwrap(); + writer.add("resources/data.bin", b"1234", crate::Compression::Stored).unwrap(); + let bytes = writer.finish_into().unwrap().into_inner(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 4, max_total_bytes: 16 }).unwrap(); + assert_eq!(archive.len(), 2); + assert_eq!(archive.entry_is_dir(0).unwrap(), Some(true)); + assert_eq!(archive.entry_is_dir(1).unwrap(), Some(false)); + assert_eq!(archive.read("resources/data.bin", 16).unwrap().unwrap(), b"1234"); + } } diff --git a/crates/zip/src/guard.rs b/crates/zip/src/guard.rs index 553e1532f..312a3bbaf 100644 --- a/crates/zip/src/guard.rs +++ b/crates/zip/src/guard.rs @@ -8,6 +8,8 @@ //! reader's limit is refused before `zip` parses anything. Anything else that is wrong is left for //! `zip` to report. +use std::io::{Read, Seek, SeekFrom}; + use crate::Error; const EOCD: &[u8; 4] = b"PK\x05\x06"; @@ -74,6 +76,86 @@ pub fn check_entry_count(bytes: &[u8], max_entries: u64) -> Result<(), Error> { Ok(()) } +/// Like [`check_entry_count`], but reads only the trailing end records and any referenced ZIP64 +/// end record from a seekable stream without buffering the archive in memory. +pub fn check_entry_count_seekable(reader: &mut R, max_entries: u64) -> Result<(), Error> { + let io_err = |e: std::io::Error| Error::NotZip(e.to_string()); + let len = reader.seek(SeekFrom::End(0)).map_err(io_err)?; + let tail_len = len.min(22 + u64::from(u16::MAX)); + let tail_start = len - tail_len; + let tail_len_usize = usize::try_from(tail_len).map_err(|_| Error::NotZip("tail too large".into()))?; + reader.seek(SeekFrom::Start(tail_start)).map_err(io_err)?; + let mut tail = vec![0u8; tail_len_usize]; + reader.read_exact(&mut tail).map_err(io_err)?; + + let u16_at = |b: &[u8], at: usize| b.get(at..at.checked_add(2)?).map(|s| u16::from_le_bytes([s[0], s[1]])); + let u32_at = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])); + let u64_at = |b: &[u8], at: usize| b.get(at..at.checked_add(8)?).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(u64::from_le_bytes); + let refuse = + |n: u64| -> Result<(), Error> { if n > max_entries { Err(Error::TooManyEntries { declared: n, limit: max_entries }) } else { Ok(()) } }; + + let mut end = tail.len(); + let mut seen = 0; + while let Some(at) = tail.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { + end = at; + seen += 1; + if seen > MAX_END_RECORDS { + return Err(Error::TooManyEndRecords(MAX_END_RECORDS)); + } + let Some(comment) = u16_at(&tail, at + 20) else { continue }; + if at + 22 + usize::from(comment) > tail.len() { + continue; + } + let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(&tail, at + 8), u16_at(&tail, at + 10), u32_at(&tail, at + 16)) else { + continue; + }; + let zip64 = total == u16::MAX || u32_at(&tail, at + 12) == Some(u32::MAX) || cd_offset == u32::MAX; + if zip64 + && let Some(locator) = at.checked_sub(20) + && tail.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) + { + let (Some(eocd64), Some(disks)) = (u64_at(&tail, locator + 8), u32_at(&tail, locator + 16)) else { continue }; + let locator_pos = tail_start + locator as u64; + if eocd64 >= locator_pos || disks > 1 { + continue; + } + let span = (locator_pos - eocd64).min(65_536); + let mut buf; + let slice = if let Some(in_tail) = eocd64.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) { + tail.get(in_tail..locator).unwrap_or_default() + } else { + let span_usize = usize::try_from(span).unwrap_or(65_536); + reader.seek(SeekFrom::Start(eocd64)).map_err(io_err)?; + buf = vec![0u8; span_usize]; + reader.read_exact(&mut buf).map_err(io_err)?; + &buf + }; + for (i, _) in slice.windows(4).enumerate().filter(|(_, w)| *w == EOCD64) { + refuse(u64_at(slice, i + 24).unwrap_or(0).max(u64_at(slice, i + 32).unwrap_or(0)))?; + } + continue; + } + if total == 0 { + return Ok(()); + } + let cd = u64::from(cd_offset); + let at_pos = tail_start + at as u64; + if cd < at_pos { + let has_cd = if let Some(in_tail) = cd.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) { + tail.get(in_tail..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) + } else { + let mut sig = [0u8; 4]; + reader.seek(SeekFrom::Start(cd)).map_err(io_err)?; + reader.read_exact(&mut sig).is_ok() && &sig == CENTRAL_HEADER + }; + if has_cd { + return refuse(u64::from(on_disk.max(total))); + } + } + } + Ok(()) +} + /// A package of one empty stored file, `a`, whose central directory lists it `entries` times (at /// most as many as fit in 64 MiB) under a ZIP64 end record that declares them all: `zip` /// parses and keeps every one of them before its caller can count them. Regression input for the @@ -125,7 +207,8 @@ pub fn zip64_entry_count_sample(entries: u64) -> Vec { #[cfg(test)] mod tests { - use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, zip64_entry_count_sample}; + use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, check_entry_count_seekable, zip64_entry_count_sample}; + use crate::Error; /// A plain package's tail: one central header at 0, then an end record declaring `entries`. @@ -200,4 +283,16 @@ mod tests { let f: Vec = (0..20).flat_map(|_| EOCD.iter().copied().chain(record)).collect(); assert_eq!(check(&f, 20_000), Err(Error::TooManyEndRecords(16))); } + + #[test] + fn seekable_entry_count_matches_in_memory_guard() { + use std::io::Cursor; + + let sample = zip64_entry_count_sample(20_001); + assert_eq!(check_entry_count_seekable(&mut Cursor::new(&sample), 20_000), Err(Error::TooManyEntries { declared: 20_001, limit: 20_000 })); + assert!(check_entry_count_seekable(&mut Cursor::new(zip64_entry_count_sample(5)), 20_000).is_ok()); + + let padded = plain(30_000, &vec![b'c'; 65_000]); + assert_eq!(check_entry_count_seekable(&mut Cursor::new(&padded), 20_000), Err(Error::TooManyEntries { declared: 30_000, limit: 20_000 })); + } } diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index ff8ce17a6..e8f8764de 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -34,11 +34,11 @@ mod seekable; mod write; pub use archive::{Archive, Limits}; -pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; +pub use guard::{check_entry_count, check_entry_count_seekable}; pub use metadata_reader::{Indexing, MetadataReader}; -pub use seekable::{InspectError, inspect_seekable}; +pub use seekable::{EntryReader, InspectError, SeekableArchive, SeekableLimits, inspect_seekable}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index 2750a0123..dfed9d643 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -1,6 +1,9 @@ -//! Checks for an already indexed, seekable ZIP archive. +//! Checks and streaming reader for seekable ZIP archives. -use std::io::{Read, Seek}; +use std::borrow::Cow; +use std::io::{self, Read, Seek}; + +use crate::{Budget, Error, MetadataReader, check_entry_count_seekable}; /// Why an indexed seekable archive exceeded its caller's limits. #[derive(Debug, thiserror::Error)] @@ -33,6 +36,222 @@ pub fn inspect_seekable(archive: &mut zip::ZipArchive, max_en Ok(()) } +/// What a [`SeekableArchive`] refuses to exceed. All numbers are the caller's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SeekableLimits { + /// Most entries the archive may declare. + pub max_entries: u64, + /// Most bytes of trailing metadata (central directory and end records) read while indexing. + pub max_metadata_bytes: u64, + /// Most bytes all the entries read from the archive may expand to together. + pub max_total_bytes: u64, +} + +/// A seekable ZIP archive that indexes only the trailing metadata and streams entry payloads +/// without buffering the archive or large entries in memory. +pub struct SeekableArchive { + zip: zip::ZipArchive>, + budget: Budget, +} + +impl SeekableArchive { + /// Indexes the trailing metadata of `reader`. The declared entry count is checked before `zip` + /// allocates for the central directory, and indexing is bounded by + /// [`SeekableLimits::max_metadata_bytes`]. + pub fn open(mut reader: R, limits: SeekableLimits) -> Result { + check_entry_count_seekable(&mut reader, limits.max_entries)?; + let (meta_reader, indexing) = MetadataReader::new(reader, limits.max_metadata_bytes).map_err(|e| Error::NotZip(e.to_string()))?; + let zip = zip::ZipArchive::new(meta_reader).map_err(|e| Error::NotZip(e.to_string()))?; + indexing.finish(); + let found = zip.len() as u64; + if found > limits.max_entries { + return Err(Error::TooManyEntries { declared: found, limit: limits.max_entries }); + } + Ok(Self { zip, budget: Budget::new("archive", limits.max_total_bytes) }) + } + + /// The number of distinct entry names. + pub fn len(&self) -> usize { + self.zip.len() + } + + pub fn is_empty(&self) -> bool { + self.zip.is_empty() + } + + /// The name at `index`, copied on demand. + pub fn entry_name(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + let name = file.name().map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(name.into_owned())) + } + + /// Whether the entry at `index` is a directory according to ZIP filename conventions. + pub fn entry_is_dir(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(file.is_dir())) + } + + /// Declared decoded and compressed sizes at `index`, without name lookup. + pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + Ok(Some((file.size(), file.compressed_size()))) + } + + /// Do two entries' compressed data ranges overlap? + pub fn has_overlapping_files(&mut self) -> Result { + self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) + } + + /// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted. + pub fn names(&self) -> impl Iterator> { + self.zip.file_names().filter_map(Result::ok) + } + + /// Is there an entry `name` (exactly as stored)? + pub fn contains(&self, name: &str) -> bool { + self.zip.index_for_name(name).is_some() + } + + /// The size entry `name` declares. It is a claim, not a measurement. + pub fn declared_size(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.size()) + } + + /// The size entry `name` takes in the archive, compressed. + pub fn compressed_size(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.compressed_size()) + } + + /// Is `name` stored without compression? + pub fn is_stored(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.compression() == zip::CompressionMethod::Stored) + } + + /// Open entry `name` for streaming reads, or `None` when there is no such entry. + /// + /// The entry may declare and expand to at most `max` bytes, and at most what is left of + /// [`SeekableLimits::max_total_bytes`]. The returned [`EntryReader`] enforces the size cap and + /// verifies the CRC-32 on EOF, charging [`Self::budget`] only when the full entry is read. + pub fn open_entry(&mut self, name: &str, max: u64) -> Result>, Error> { + let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.open_entry_index_named(index, name, max) + } + + /// Open the entry at `index` for streaming reads under the same rules as [`Self::open_entry`]. + pub fn open_entry_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); + self.open_entry_index_named(index, &name, max) + } + + fn open_entry_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + let file = self.zip.by_index(index).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?; + let declared = file.size(); + if declared > max { + return Err(Error::EntryTooLarge { name: name.to_string(), limit: max }); + } + if declared > self.budget.remaining() { + return Err(Error::BudgetSpent { name: name.to_string(), limit: self.budget.limit() }); + } + Ok(Some(EntryReader { file, budget: &mut self.budget, declared, limit: declared, read: 0, finished: false })) + } + + /// Read all bytes of entry `name` into memory, or `None` when there is no such entry. + pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { + let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.read_index_named(index, name, max) + } + + /// Read all bytes of the entry at `index` into memory. + pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); + self.read_index_named(index, &name, max) + } + + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + let Some(mut reader) = self.open_entry_index_named(index, name, max)? else { return Ok(None) }; + let mut out = Vec::with_capacity(usize::try_from(reader.declared).unwrap_or(64 * 1024).min(64 * 1024)); + reader.read_to_end(&mut out).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?; + Ok(Some(out)) + } + + /// The total budget: what the entries read so far have used, and what is left. + pub fn budget(&self) -> &Budget { + &self.budget + } + + /// The total budget, for a caller with its own charging rule. + pub fn budget_mut(&mut self) -> &mut Budget { + &mut self.budget + } +} + +/// Streaming reader for a single entry opened from [`SeekableArchive`]. +/// +/// Enforces the declared and caller-provided byte limits and charges the archive's [`Budget`] +/// once the full entry has been read and its CRC-32 verified. +pub struct EntryReader<'a, R: Read> { + file: zip::read::ZipFile<'a, MetadataReader>, + budget: &'a mut Budget, + declared: u64, + limit: u64, + read: u64, + finished: bool, +} + +impl EntryReader<'_, R> { + /// The uncompressed size declared by the entry header. + pub fn declared_size(&self) -> u64 { + self.declared + } +} + +impl Read for EntryReader<'_, R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.finished || buf.is_empty() { + return Ok(0); + } + let remaining = self.limit.saturating_sub(self.read); + let max_read = usize::try_from(remaining.saturating_add(1)).unwrap_or(usize::MAX).min(buf.len()); + let n = self.file.read(&mut buf[..max_read])?; + if n == 0 { + if self.read < self.declared { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!("entry ended after {} bytes, declared {}", self.read, self.declared), + )); + } + self.budget.charge(self.read).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; + self.finished = true; + return Ok(0); + } + let next = self.read.saturating_add(n as u64); + if next > self.limit { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("entry exceeds declared size of {} bytes", self.limit))); + } + self.read = next; + Ok(n) + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -72,4 +291,77 @@ mod tests { let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner(); assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok()); } + + #[test] + fn seekable_archive_streams_stored_and_deflated_entries_within_limits() { + let mut writer = crate::Writer::new(); + let big: Vec = (0..50_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect(); + writer.add("a.bin", &big, crate::Compression::Deflated).unwrap(); + writer.add("b.bin", b"hello stored", crate::Compression::Stored).unwrap(); + let bytes = writer.finish().unwrap(); + + let limits = SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 250_000 }; + let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap(); + assert_eq!(archive.len(), 2); + assert!(archive.contains("a.bin")); + assert_eq!(archive.declared_size("a.bin"), Some(big.len() as u64)); + + // Stream in small chunks without loading via Vec in one shot. + let mut reader = archive.open_entry("a.bin", big.len() as u64).unwrap().unwrap(); + let mut out = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = reader.read(&mut chunk).unwrap(); + if n == 0 { + break; + } + out.extend_from_slice(&chunk[..n]); + } + assert_eq!(out, big); + drop(reader); + assert_eq!(archive.budget().used(), big.len() as u64); + + let b = archive.read("b.bin", 100).unwrap().unwrap(); + assert_eq!(b, b"hello stored"); + assert_eq!(archive.budget().used(), big.len() as u64 + 12); + } + + #[test] + fn seekable_archive_enforces_entry_count_size_budget_and_crc() { + let sample = crate::zip64_entry_count_sample(20_001); + let err = SeekableArchive::open( + Cursor::new(sample), + SeekableLimits { max_entries: 20_000, max_metadata_bytes: 16 << 20, max_total_bytes: 1 << 20 }, + ) + .err() + .unwrap(); + assert!(matches!(err, Error::TooManyEntries { declared: 20_001, limit: 20_000 }), "{err:?}"); + + let mut writer = crate::Writer::new(); + writer.add("cat.lrcat", &[7u8; 1024], crate::Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + + // Entry larger than per-entry max is refused before reading. + let mut archive = + SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 }) + .unwrap(); + assert!(matches!(archive.open_entry("cat.lrcat", 1023), Err(Error::EntryTooLarge { limit: 1023, .. }))); + assert_eq!(archive.budget().used(), 0); + + // Entry larger than remaining budget is refused. + let mut tight = + SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 512 }).unwrap(); + assert!(matches!(tight.open_entry("cat.lrcat", 2048), Err(Error::BudgetSpent { limit: 512, .. }))); + + // Corrupted payload fails CRC check and does not charge budget. + let mut bad = bytes.clone(); + bad[45] ^= 0xFF; + let mut bad_archive = + SeekableArchive::open(Cursor::new(&bad), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 }).unwrap(); + let mut reader = bad_archive.open_entry("cat.lrcat", 2048).unwrap().unwrap(); + let mut sink = Vec::new(); + assert!(reader.read_to_end(&mut sink).is_err()); + drop(reader); + assert_eq!(bad_archive.budget().used(), 0); + } } diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 451729759..76bf753a6 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -1,6 +1,6 @@ //! A ZIP archive being written. -use std::io::{Cursor, Write}; +use std::io::{Cursor, Seek, Write}; use crate::Error; @@ -16,21 +16,21 @@ pub enum Compression { Level(u8), } -/// A ZIP archive being written into memory. The output is deterministic: the same (1980) +/// A ZIP archive being written. The output is deterministic: the same (1980) /// timestamp on every entry. Entries are written in the order they are added. -pub struct Writer { - zip: zip::ZipWriter>>, +pub struct Writer>> { + zip: zip::ZipWriter, legacy_utf8: bool, } -impl Default for Writer { - fn default() -> Writer { +impl Default for Writer>> { + fn default() -> Writer>> { Writer { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), legacy_utf8: false } } } -impl Writer { - pub fn new() -> Writer { +impl Writer>> { + pub fn new() -> Writer>> { Writer::default() } @@ -38,10 +38,33 @@ impl Writer { /// /// This keeps stored archives byte-for-byte stable for existing users while still using the /// shared writer for entry encoding and validation. - pub fn legacy_utf8() -> Writer { + pub fn legacy_utf8() -> Writer>> { Writer { legacy_utf8: true, ..Writer::default() } } + /// The finished archive. + pub fn finish(self) -> Result, Error> { + let mut bytes = self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string()))?; + if self.legacy_utf8 { + patch_legacy_utf8_headers(&mut bytes)?; + } + Ok(bytes) + } +} + +impl Writer { + /// Starts writing an archive directly to a seekable destination without buffering the whole + /// archive in memory. + pub fn to_writer(destination: W) -> Self { + Self { zip: zip::ZipWriter::new(destination), legacy_utf8: false } + } + + /// Adds a directory entry with the deterministic 1980 timestamp. + pub fn add_directory(&mut self, name: &str) -> Result<(), Error> { + let options = zip::write::SimpleFileOptions::default().last_modified_time(zip::DateTime::default()); + self.zip.add_directory(name, options).map_err(|e| Error::Write(format!("{name}: {e}"))) + } + /// Adds an entry from a byte slice. A name the archive already has is an error. pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> { self.add_entry(name, data, compression, 1, data.len() as u64 >= u64::from(u32::MAX) / 2) @@ -98,13 +121,18 @@ impl Writer { write(&mut self.zip).map_err(|e| fail(&e)) } - /// The finished archive. - pub fn finish(self) -> Result, Error> { - let mut bytes = self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string()))?; + /// Finishes writing and returns the underlying destination. + /// + /// Legacy UTF-8 mode requires [`Writer::finish`] to apply its in-memory header patch. + /// Calling this method in legacy mode consumes the writer and returns [`Error::Write`]; + /// use `finish` instead when constructing a writer with [`Writer::legacy_utf8`]. + pub fn finish_into(self) -> Result { + // A generic destination need not support reads or header patching. Never silently + // return an archive that omits the byte-compatibility contract of legacy mode. if self.legacy_utf8 { - patch_legacy_utf8_headers(&mut bytes)?; + return Err(Error::Write("legacy UTF-8 output requires Writer::finish".into())); } - Ok(bytes) + self.zip.finish().map_err(|e| Error::Write(e.to_string())) } } @@ -184,3 +212,27 @@ fn patch_legacy_utf8_headers(bytes: &mut [u8]) -> Result<(), Error> { } Ok(()) } + +#[cfg(test)] +mod finish_tests { + use super::*; + + #[test] + fn legacy_ascii_output_requires_the_header_patching_finish_path() { + let mut legacy = Writer::legacy_utf8(); + legacy.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + assert!(matches!(legacy.finish_into(), Err(Error::Write(message)) + if message == "legacy UTF-8 output requires Writer::finish")); + + let mut legacy = Writer::legacy_utf8(); + legacy.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + let bytes = legacy.finish().unwrap(); + assert_eq!(get_u16(&bytes, 6).unwrap() & 0x0800, 0x0800); + + let mut ordinary = Writer::to_writer(Cursor::new(Vec::new())); + ordinary.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + let bytes = ordinary.finish_into().unwrap().into_inner(); + let mut archive = crate::Archive::open(&bytes, crate::Limits { max_entries: 1, max_total_bytes: 32 }).unwrap(); + assert_eq!(archive.read("a.txt", 32).unwrap().unwrap(), b"ordinary text"); + } +} diff --git a/design/layers/craft-ui-contract/contract.toml b/design/layers/craft-ui-contract/contract.toml index b39d88b37..6206cbe3c 100644 --- a/design/layers/craft-ui-contract/contract.toml +++ b/design/layers/craft-ui-contract/contract.toml @@ -3,3 +3,8 @@ config_version = 1 [[module]] path = "contract" layer = 4 + +# memo depends only on std and runtime::env, so it sits with the runtime modules that use it. +[[module]] +path = "contract::memo" +layer = 2 diff --git a/docs/contract-api.md b/docs/contract-api.md index 5dab0dbaa..b69e2aac7 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2134,7 +2134,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::MeasureCx`: `pub struct MeasureCx<'a, C: Component> { pub env: EnvView<'a>, pub style: &'a C::Style, pub resolved: &'a Resolved<'a>, pub proposal: Proposal, pub room: Option, pub ui: &'a Ui, pub tokens: &'a UiTokens, pub id: Id }`. What `measure` reads: step 5's view of the environment, the style, the resolved props and the shown value. - `pub fn value(&self) -> Option<&'a ValueOf>`. The shown value; it has the stage's lifetime, so a borrow of `cx` is not held. - `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. - - `pub fn resolve_command(&self, command: impl Into) -> Option`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above + - `pub fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above - `pub fn column_room(&self) -> Option`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up - `pub fn label(&self) -> Label`. The label as given. @@ -3107,10 +3107,12 @@ Per-pass and per-frame services and the one egui adapter. The command board: the registry and typed sets, per-frame state, the queue, firing and the gate (spec 11). - `craft_ui::runtime::commands::CommandGate`: `pub struct CommandGate`. The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an - - `pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self`. A gate that lets `allows` commands through. + - `pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self`. A gate that lets through the commands `allows` accepts under `props`; the runtime asks it once per command while the props' key stays the same. +- `craft_ui::runtime::commands::CommandStates`: `pub struct CommandStates`. The app-scope command states an app holds, in a `Tracked` it hands to `CommandInput::states`. + - `pub fn new() -> Self`, `pub fn set(&mut self, command: impl Into, state: CommandState)`, `pub fn remove(&mut self, command: &CommandRef) -> Option`, `pub fn get(&self, command: &CommandRef) -> Option<&CommandState>`. - `craft_ui::runtime::commands::CommandInput`: `pub struct CommandInput`. App-scope command state for this frame, set from app state before the pass. - `pub fn new() -> Self`. No state, no overrides and no gate. - - `pub fn state(mut self, command: impl Into, state: CommandState) -> Self`. The state of an app-scope command. + - `pub fn states(mut self, states: &Tracked) -> Self`. The app-scope command states the app holds; the runtime reads them again only when the revision moves. - `pub fn overrides(mut self, overrides: Arc) -> Self`. The user's binding overrides; the keymap is rebuilt when the `Arc` changes. - `pub fn gate(mut self, gate: CommandGate) -> Self`. The one gate over commands. - `craft_ui::runtime::commands::CommandSet`: `pub trait CommandSet: Copy + Send + Sync + 'static`. A typed set of commands, written by `#[derive(CommandSet)]`. @@ -3133,13 +3135,13 @@ The command board: the registry and typed sets, per-frame state, the queue, firi - `fn publish(&mut self, command: impl Into, state: CommandState)`. This frame's state of a scoped command, for this instance. Publishing an app-scope command here is a - `fn take_command(&mut self) -> Option<(S, Fired)>`. The next command of set `S` routed to this instance this pass; each is taken once, so a discard pass does - `fn take_step(&mut self, can_undo: bool, can_redo: bool) -> Option`. Declares Undo and Redo on the innermost instance around this context, enabled as `can_undo` and `can_redo` - - `fn resolve_command(&self, command: impl Into) -> Option`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above + - `fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above - `craft_ui::runtime::commands::FirePhase`: `pub enum FirePhase { Press, Repeat, Release }`. The phase of the key press that fired a command. - `craft_ui::runtime::commands::FireSource`: `pub enum FireSource { Key, Menu, Palette, Pointer, Automation, Access }`. Where a fired command came from. - `craft_ui::runtime::commands::Fired`: `pub struct Fired { pub command: CommandRef, pub target: Option, pub source: FireSource, pub phase: FirePhase, pub cycle: bool, pub alt_variant: bool }`. A command a surface or a key fired, as the instance or the app takes it. - `craft_ui::runtime::commands::ResolvedCommand`: `pub struct ResolvedCommand { pub label: Arc, pub icon: Option>, pub chord: Option, pub enabled: bool, pub checked: Option, pub marked: bool, pub hint: Option>, pub kind: CommandKind, pub instance: Option }`. A command as a surface shows and fires it. - `craft_ui::runtime::commands::fire`: `pub fn fire(ctx: &Context, command: impl Into, source: FireSource) -> bool`. Fires `command` from a surface that has no component of its own: a menu, the palette or automation. Scoped -- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state +- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> Arc`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state - `craft_ui::runtime::commands::Binding`: re-export of `craft_keymap::Binding` (outside these crates). - `craft_ui::runtime::commands::ChromeCommand`: `pub enum ChromeCommand { TogglePanels, TogglePanelsKeepTools }`. The `window` commands that hide the panels of the window they run in. - `pub const ALL: [ChromeCommand; 2]`. Both commands. diff --git a/docs/glossary.md b/docs/glossary.md index f49a9d90a..317b2a858 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -49,7 +49,7 @@ One row per name in the author table (Overview) and per `pub` item a component a | `CommandGate` | The one gate that can disable commands (dialog open, workspace, recorder, pending operation) | `craft_ui::runtime::commands` | 11.3 | | `Commands` | The context trait on `Cx`, `BodyCx` and `ItemCx` for commands and the clipboard | `craft_ui::runtime::commands` | 11.3 | | `CommandSet` | A typed set of commands with one scope, written by `#[derive(CommandSet)]` and read with `take_command::()` | craft-keymap (trait), `craft_ui::runtime::commands` (board) | 11.2, 11.3 | -| `CommandState`, `CommandInput` | A command's state this frame, and the app-scope states in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | +| `CommandState`, `CommandStates`, `CommandInput` | A command's state, the app-scope states an app holds in a `Tracked`, and the frame's command input in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | | `Common` | The props every component has, with no public fields | `craft_ui::contract` | 3.1 | | Component | Any type implementing the core trait | `craft_ui::contract` | 1.2 | | `ComponentStyle` | The trait every `type Style` implements, usually with `#[derive(ComponentStyle)]` | `craft_ui::style` | 4.3 |