From b964fed1c567b829a8cf5daf9a197ab1d4757064 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:27:49 +0100 Subject: [PATCH 001/311] image-codecs: add jpeg_worst_case_coefficients (#778) (#2063) A conservative pre-decode coefficient budget for hostile JPEG headers: the larger of JpegInfo::held_coefficients and a whole-picture estimate over every progressive frame header (SOF2/6/10/14, any precision, sampling clamped to 1..=4), with the costliest frame charged at the first frame's size when the header can't be followed. held_coefficients is unchanged. Co-authored-by: Claude Opus 5.5 (cherry picked from commit ea0218294591cef788a8efe9e5b31f1d8dafc6a6) --- crates/image-codecs/src/codecs/jpeg.rs | 241 +++++++++++++++++++++++++ crates/image-codecs/src/lib.rs | 9 + 2 files changed, 250 insertions(+) diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 415a5d717..56593a5f5 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -86,6 +86,83 @@ fn held_coefficients(marker: u8, seg: &[u8], scan_components: Option) -> u64 factors.iter().map(|&(fh, fv)| mcus * fh * fv * 64 * 2).sum() } +/// Bytes of DCT coefficients to budget for before decoding hostile `b`: the larger of +/// [`crate::JpegInfo::held_coefficients`]'s rule (first frame; SOF2, or SOF0/SOF1 whose first +/// scan lacks components; 8-bit only; sampling factors as written) and a coarser one that +/// keeps a progressive JPEG's coefficients for the whole picture: +/// - every SOF2, SOF6, SOF10 and SOF14 header before the first scan counts, at any precision, and +/// the largest wins; each charges 2 bytes a coefficient: per component, `2 * 64 * h * v` per +/// MCU, with `h` and `v` clamped to 1..=4 and the MCUs covering the frame at the largest `h`, `v`; +/// - a header that can't be followed (a segment that is cut, a length under 2, a frame header +/// without its components, no `0xFF` where a marker belongs) charges the costliest frame, +/// four components sampled 4 × 4, at the first frame's size (as `scan_metadata` reads it), and 0 without one. +/// +/// Never less than either rule. Frames `craft-jpeg` decodes (arithmetic, lossless, 12-bit) +/// enforce `max_alloc` on their own buffers, and SOF6/SOF14 (hierarchical) are not decoded at all, +/// so charging them is only a conservative budget. Arithmetic saturates; the scan is linear. +pub(crate) fn worst_case_coefficients(b: &[u8]) -> u64 { + let m = scan_metadata(b); + let mut at = 2usize; + let mut most = 0u64; + let first: Option<(u64, u64)> = m.frame.map(|(w, h, _)| (u64::from(w), u64::from(h))); + let mut broken = false; + while !broken { + if b.get(at) != Some(&0xFF) { + broken = true; + break; + } + while b.get(at) == Some(&0xFF) { + at += 1; + } + let Some(&code) = b.get(at) else { + broken = true; + break; + }; + at += 1; + match code { + 0xD8 | 0x01 | 0xD0..=0xD7 => continue, + 0xD9 | 0xDA => break, + _ => {} + } + let len = match (b.get(at), b.get(at + 1)) { + (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), + _ => 0, + }; + let Some(seg) = (len >= 2).then(|| b.get(at + 2..at + len)).flatten() else { + broken = true; + break; + }; + if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { + match progressive_frame_coefficients(seg) { + Some(held) => most = most.max(held), + None => { + broken = true; + break; + } + } + } + at += len; + } + if broken && let Some((w, h)) = first { + let mcus = w.div_ceil(32).saturating_mul(h.div_ceil(32)); + most = most.max(mcus.saturating_mul(2 * 64 * 16 * 4)); + } + most.max(m.held_coefficients) +} + +/// [`worst_case_coefficients`]'s charge for one frame header `sof` (after its length). +fn progressive_frame_coefficients(sof: &[u8]) -> Option { + let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); + let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); + let n = usize::from(*sof.get(5)?); + let comps = sof.get(6..6usize.checked_add(n.checked_mul(3)?)?)?; + let factors: Vec<(u64, u64)> = + comps.as_chunks::<3>().0.iter().map(|&[_, f, _]| (u64::from(f >> 4).clamp(1, 4), u64::from(f & 15).clamp(1, 4))).collect(); + let (hmax, vmax) = factors.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); + let mcus = width.div_ceil(8 * hmax).saturating_mul(height.div_ceil(8 * vmax)); + Some(factors.iter().fold(0u64, |sum, &(h, v)| sum.saturating_add(mcus.saturating_mul(2 * 64 * h * v)))) +} + /// Walk the marker segments up to SOS and collect metadata. pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { let mut m = JpegMeta::default(); @@ -825,6 +902,170 @@ mod tests { assert_eq!(held(&frame(0xC2, 12, &[0x11, 0x11, 0x11], None)), Some(0)); } + /// The consumer's own estimate (WordCraft's `jpeg_coefficients`), ported as the oracle that + /// `worst_case_coefficients` must never undercut. + fn oracle(bytes: &[u8]) -> u64 { + fn worst(bytes: &[u8]) -> u64 { + let Some((w, h)) = info(bytes).map(|i| (i.width, i.height)) else { return 0 }; + let mcus = u64::from(w).div_ceil(32) * u64::from(h).div_ceil(32); + mcus.saturating_mul(2 * 64 * 16 * 4) + } + fn frame(sof: &[u8]) -> Option { + let height = u64::from(u16::from_be_bytes([*sof.get(1)?, *sof.get(2)?])); + let width = u64::from(u16::from_be_bytes([*sof.get(3)?, *sof.get(4)?])); + let n = usize::from(*sof.get(5)?); + let s: Vec<(u64, u64)> = sof + .get(6..6 + 3 * n)? + .as_chunks::<3>() + .0 + .iter() + .map(|&[_, s, _]| (u64::from(s >> 4).clamp(1, 4), u64::from(s & 15).clamp(1, 4))) + .collect(); + let (hm, vm) = s.iter().fold((1, 1), |(h, v), &(a, b)| (h.max(a), v.max(b))); + let mcus = width.div_ceil(8 * hm).checked_mul(height.div_ceil(8 * vm))?; + s.iter().try_fold(0u64, |sum, &(h, v)| sum.checked_add(mcus.checked_mul(2 * 64 * h * v)?)) + } + let mut at = 2; + let mut most = 0u64; + loop { + if bytes.get(at) != Some(&0xFF) { + return worst(bytes).max(most); + } + while bytes.get(at) == Some(&0xFF) { + at += 1; + } + let Some(&code) = bytes.get(at) else { return worst(bytes).max(most) }; + at += 1; + match code { + 0xD8 | 0x01 | 0xD0..=0xD7 => continue, + 0xD9 | 0xDA => return most, + _ => {} + } + let len = match (bytes.get(at), bytes.get(at + 1)) { + (Some(&hi), Some(&lo)) => usize::from(u16::from_be_bytes([hi, lo])), + _ => 0, + }; + let Some(seg) = bytes.get(at + 2..at + len).filter(|_| len >= 2) else { return worst(bytes).max(most) }; + if matches!(code, 0xC2 | 0xC6 | 0xCA | 0xCE) { + let Some(h) = frame(seg) else { return worst(bytes).max(most) }; + most = most.max(h); + } + at += len; + } + } + + /// A JPEG header: each frame is (marker, precision, width, height, sampling bytes), then an + /// optional scan of `scan` components, then EOI. + fn header(frames: &[(u8, u8, u16, u16, &[u8])], scan: Option) -> Vec { + let mut b = vec![0xFF, 0xD8]; + for &(marker, precision, w, h, f) in frames { + b.extend_from_slice(&[0xFF, marker]); + b.extend_from_slice(&(8 + 3 * f.len() as u16).to_be_bytes()); + b.push(precision); + b.extend_from_slice(&h.to_be_bytes()); + b.extend_from_slice(&w.to_be_bytes()); + b.push(f.len() as u8); + for (i, &s) in f.iter().enumerate() { + b.extend_from_slice(&[i as u8 + 1, s, 0]); + } + } + if let Some(n) = scan { + b.extend_from_slice(&[0xFF, 0xDA, 0, 6 + 2 * n, n]); + (1..=n).for_each(|c| b.extend_from_slice(&[c, 0])); + b.extend_from_slice(&[0, 63, 0]); + } + b.extend_from_slice(&[0xFF, 0xD9]); + b + } + + /// Never less than the oracle or `held_coefficients`; equal to the larger on valid headers. + #[test] + fn worst_case_coefficients_covers_both_rule_sets() { + const C3: &[u8] = &[0x22, 0x11, 0x11]; + const G: &[u8] = &[0x11]; + let cases: Vec> = vec![ + header(&[(0xC0, 8, 640, 480, C3)], Some(3)), + header(&[(0xC0, 8, 640, 480, G)], Some(1)), + header(&[(0xC0, 8, 640, 480, C3)], Some(1)), + header(&[(0xC1, 8, 640, 480, C3)], None), + header(&[(0xC2, 8, 640, 480, C3)], Some(1)), + header(&[(0xC2, 12, 640, 480, C3)], Some(1)), + header(&[(0xC6, 8, 640, 480, C3)], None), + header(&[(0xCA, 8, 640, 480, C3)], None), + header(&[(0xCE, 8, 640, 480, C3)], None), + header(&[(0xC0, 8, 64, 64, G), (0xC2, 8, 6000, 4000, C3), (0xC2, 8, 100, 100, C3)], Some(1)), + header(&[(0xC2, 8, 640, 480, &[0x00, 0x00, 0x00])], None), + header(&[(0xC2, 8, 640, 480, &[0xFF, 0xFF, 0xFF, 0xFF])], None), + header(&[(0xC2, 8, 65535, 65535, &[0x44; 4])], None), + header(&[(0xC0, 8, 65535, 65535, &[0xFF; 4])], Some(1)), + header(&[], None), + vec![0xFF, 0xD8], + vec![], + b"not a jpeg at all".to_vec(), + ]; + for b in &cases { + let held = scan_metadata(b).held_coefficients; + let got = worst_case_coefficients(b); + assert!(got >= oracle(b) && got >= held, "{b:02x?}"); + assert!(got >= info(b).map_or(0, |i| i.held_coefficients)); + } + let at = |i: usize| worst_case_coefficients(&cases[i]); + // Equal to the oracle where the shared rule charges nothing extra. + for i in [0, 1, 6, 7, 8, 9, 10, 12, 14] { + assert_eq!(at(i), oracle(&cases[i]), "case {i}"); + } + // Where it does, the shared figure wins (the oracle misses a short first scan). + assert_eq!(oracle(&cases[2]), 0); + assert_eq!(at(2), scan_metadata(&cases[2]).held_coefficients); + // Unclamped factors (15 × 15) charge the shared rule more than the clamped oracle. + assert_eq!(at(11), scan_metadata(&cases[11]).held_coefficients); + assert!(at(11) > oracle(&cases[11])); + assert!(at(2) > 0 && at(3) == 0 && at(0) == 0); + // 12-bit and arithmetic progressive frames are charged though craft-jpeg limits itself. + assert_eq!(at(5), at(4)); + // Sampling factors clamp: 0 acts as 1, 15 as 4. + assert_eq!(at(10), 80 * 60 * 3 * 128); + assert_eq!(at(12), 2048 * 2048 * 4 * 2 * 64 * 16); + // The largest of several frames wins. + assert_eq!(at(9), oracle(&header(&[(0xC2, 8, 6000, 4000, C3)], None))); + } + + /// A cut header charges the costliest frame at its size; every prefix and random damage stays + /// bounded, never panics and never undercuts the oracle. + #[test] + fn worst_case_coefficients_hostile_input() { + let full = header(&[(0xC2, 8, 6000, 4000, &[0x22, 0x11, 0x11])], Some(1)); + let cut = &full[..full.len() - 8]; + // Cut inside the component list: a frame the scan can't read, at its own size. + let sof_cut = &full[..14]; + assert_eq!(worst_case_coefficients(sof_cut), oracle(sof_cut)); + assert_eq!(worst_case_coefficients(cut), oracle(cut)); + let mut bases = vec![full.clone(), header(&[(0xC0, 8, 6000, 4000, &[0x11; 3])], Some(1))]; + bases.push(header(&[(0xC2, 8, 65535, 65535, &[0xFF; 4])], None)); + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let mut next = move || { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize + }; + for base in &bases { + for n in 0..=base.len() { + let b = &base[..n]; + let got = worst_case_coefficients(b); + assert!(got >= oracle(b) && got < 1 << 50); + } + for _ in 0..2000 { + let mut b = base.clone(); + for _ in 0..=next() % 4 { + let i = next() % b.len(); + b[i] = next() as u8; + } + b.truncate(next() % (b.len() + 1)); + let got = worst_case_coefficients(&b); + assert!(got >= oracle(&b) && got >= scan_metadata(&b).held_coefficients && got < 1 << 50); + } + } + } + /// An APP1 Extended XMP fragment (GUID, total size, offset, data). fn extended_xmp(offset: u32) -> Vec { let mut seg = EXTENDED_XMP_HEADER.to_vec(); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index dc2ac2933..47e3f12e3 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -307,6 +307,15 @@ pub fn jpeg_info(bytes: &[u8]) -> Option { jpeg::info(bytes) } +/// Bytes of DCT coefficients to budget for a JPEG before decoding it: never less than +/// [`JpegInfo::held_coefficients`] nor than the whole-picture estimate of every progressive +/// frame header (SOF2, SOF6, SOF10, SOF14 at any precision, sampling clamped to 1..=4), and the +/// costliest frame at the first size read when the header can't be followed. 0 without a +/// readable frame. See the function body's rules for the precise charges. +pub fn jpeg_worst_case_coefficients(bytes: &[u8]) -> u64 { + jpeg::worst_case_coefficients(bytes) +} + /// PCX's dimensions are available from its fixed-size header without decoding the RLE rows. pub fn pcx_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { codecs::pcx::dimensions(bytes) From 3e6e0de90dcb7296149d51f9be4a6db744ef9b57 Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:27:53 +0100 Subject: [PATCH 002/311] image-codecs: header-only PNG pixel model and WebP alpha probes (#778) (#2064) png_probe::pixel_model reads width, height, bit depth, colour type and tRNS presence from IHDR and the chunk headers before IDAT without inflating iCCP; PixelModel::bytes_per_pixel and has_alpha give a caller's pixel size and alpha. webp_probe::has_alpha reads the VP8X alpha flag, the VP8L alpha_is_used bit, and treats plain VP8 as opaque. Differential tests compare against WordCraft's png_chunks as an oracle. Co-authored-by: Claude Opus 5.5 (cherry picked from commit 1928693fbb7a4f8e6b945e614b2fac3e181476ea) --- crates/image-codecs/src/png_probe.rs | 223 ++++++++++++++++++++++++++ crates/image-codecs/src/webp_probe.rs | 54 +++++++ 2 files changed, 277 insertions(+) diff --git a/crates/image-codecs/src/png_probe.rs b/crates/image-codecs/src/png_probe.rs index 73f1199eb..e7af74334 100644 --- a/crates/image-codecs/src/png_probe.rs +++ b/crates/image-codecs/src/png_probe.rs @@ -136,6 +136,93 @@ pub fn color_chunks(b: &[u8]) -> Option { Some(result) } +/// Most chunks [`pixel_model`] walks before the image data; each chunk is at least 12 bytes. +const MAX_PROBE_CHUNKS: usize = 1 << 16; + +/// Pixel model of a PNG, from `IHDR` and the chunk headers before the first `IDAT`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PixelModel { + pub width: u32, + pub height: u32, + /// `IHDR` bit depth (1, 2, 4, 8 or 16). + pub bit_depth: u8, + /// `IHDR` colour type (0 grey, 2 RGB, 3 palette, 4 grey+alpha, 6 RGBA). + pub color_type: u8, + /// A `tRNS` chunk precedes the image data; it adds alpha to grey, RGB and palette images. + pub has_trns: bool, +} + +impl PixelModel { + /// Channels of the decoded buffer (palette expands to RGB; `tRNS` adds an alpha channel). + pub fn channels(&self) -> u8 { + let base = match self.color_type { + 0 => 1, + 2 | 3 => 3, + 4 => 2, + _ => 4, + }; + base + u8::from(self.has_trns && matches!(self.color_type, 0 | 2 | 3)) + } + + /// Bytes per pixel of the buffer a decoder that expands sub-byte samples to 8 bits gives: + /// `channels * (2 if bit_depth == 16 else 1)`. + pub fn bytes_per_pixel(&self) -> u8 { + self.channels() * if self.bit_depth == 16 { 2 } else { 1 } + } + + /// Whether the image has transparency (alpha colour type or `tRNS`). + pub fn has_alpha(&self) -> bool { + matches!(self.color_type, 4 | 6) || self.has_trns + } +} + +/// Dimensions, bit depth, colour type and `tRNS` presence without inflating anything (an `iCCP` +/// profile is skipped, not decompressed). Walks at most 65,536 chunk headers and stops at `IDAT`; +/// `IEND` or the end of the input before `IDAT` is an error. Does not validate CRCs. +/// A caller gets its `(width, height, bytes_per_pixel, alpha)` as +/// `(m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha())`. +pub fn pixel_model(b: &[u8]) -> Result { + if !b.starts_with(b"\x89PNG\r\n\x1a\n") { + return Err(err("bad signature")); + } + let be32 = |p: usize| b.get(p..p.checked_add(4)?).and_then(|v| <[u8; 4]>::try_from(v).ok()).map(u32::from_be_bytes); + if be32(8) != Some(13) || b.get(12..16) != Some(b"IHDR") { + return Err(err("missing IHDR")); + } + let ihdr = b.get(16..29).ok_or_else(|| err("truncated IHDR"))?; + let (width, height) = (be32(16).unwrap_or(0), be32(20).unwrap_or(0)); + let (bit_depth, color_type) = (ihdr[8], ihdr[9]); + if width == 0 || height == 0 || width > i32::MAX as u32 || height > i32::MAX as u32 { + return Err(err("dimensions out of range")); + } + let depth_ok = match color_type { + 0 => matches!(bit_depth, 1 | 2 | 4 | 8 | 16), + 3 => matches!(bit_depth, 1 | 2 | 4 | 8), + 2 | 4 | 6 => matches!(bit_depth, 8 | 16), + _ => false, + }; + if !depth_ok { + return Err(err("invalid IHDR")); + } + let mut has_trns = false; + let mut p = 8usize; + for _ in 0..MAX_PROBE_CHUNKS { + let len = be32(p).ok_or_else(|| err("truncated"))?; + let kind = p.checked_add(4).and_then(|k| b.get(k..k.checked_add(4)?)).ok_or_else(|| err("truncated"))?; + match kind { + b"IDAT" => return Ok(PixelModel { width, height, bit_depth, color_type, has_trns }), + b"IEND" => return Err(err("no image data")), + b"tRNS" => has_trns = true, + _ => {} + } + if len > i32::MAX as u32 { + return Err(err("chunk length out of range")); + } + p = p.checked_add(12).and_then(|q| q.checked_add(len as usize)).ok_or_else(|| err("truncated"))?; + } + Err(CodecError::LimitExceeded("PNG chunk count".into())) +} + #[cfg(test)] mod tests { use super::*; @@ -187,4 +274,140 @@ mod tests { assert!(!color.srgb); assert!(color_chunks(b"not png").is_none()); } + + /// WordCraft's `png_chunks` (crates/geom/src/picture.rs) as the differential oracle. + fn oracle(bytes: &[u8]) -> Option<(u32, u32, u64, bool)> { + let be = |at: usize| bytes.get(at..at.checked_add(4)?).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_be_bytes); + if bytes.get(12..16) != Some(b"IHDR".as_slice()) { + return None; + } + let (width, height) = (be(16)?, be(20)?); + let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?); + let mut trns = false; + let mut at = 8usize; + loop { + let len = usize::try_from(be(at)?).ok()?; + match bytes.get(at.checked_add(4)?..at.checked_add(8)?)? { + b"IDAT" => break, + b"IEND" => return None, + b"tRNS" => trns = true, + _ => {} + } + at = at.checked_add(12)?.checked_add(len)?; + } + let (channels, alpha) = match color { + 0 => (1 + u64::from(trns), trns), + 2 | 3 => (3 + u64::from(trns), trns), + 4 => (2, true), + 6 => (4, true), + _ => return None, + }; + Some((width, height, channels * if depth == 16 { 2 } else { 1 }, alpha)) + } + + fn tuple(b: &[u8]) -> Option<(u32, u32, u64, bool)> { + pixel_model(b).ok().map(|m| (m.width, m.height, u64::from(m.bytes_per_pixel()), m.has_alpha())) + } + + fn png_with(depth: u8, color: u8, before_idat: &[(&[u8; 4], Vec)]) -> Vec { + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&5u32.to_be_bytes()); + ihdr.extend_from_slice(&7u32.to_be_bytes()); + ihdr.extend_from_slice(&[depth, color, 0, 0, 0]); + chunk(&mut bytes, b"IHDR", &ihdr); + for (k, d) in before_idat { + chunk(&mut bytes, k, d); + } + chunk(&mut bytes, b"IDAT", &[1, 2, 3]); + chunk(&mut bytes, b"IEND", &[]); + bytes + } + + #[test] + fn pixel_model_matches_oracle_for_every_color_type_depth_and_trns() { + let valid: [(u8, &[u8]); 5] = [(0, &[1, 2, 4, 8, 16]), (2, &[8, 16]), (3, &[1, 2, 4, 8]), (4, &[8, 16]), (6, &[8, 16])]; + for (color, depths) in valid { + for &depth in depths { + for trns in [false, true] { + let extra: Vec<(&[u8; 4], Vec)> = if trns { vec![(b"tRNS", vec![0, 0])] } else { vec![] }; + let bytes = png_with(depth, color, &extra); + assert!(tuple(&bytes).is_some(), "color {color} depth {depth}"); + assert_eq!(tuple(&bytes), oracle(&bytes), "color {color} depth {depth} trns {trns}"); + } + } + } + } + + #[test] + fn pixel_model_known_values() { + let m = pixel_model(&png_with(16, 2, &[(b"tRNS", vec![0; 6])])).unwrap(); + assert_eq!((m.width, m.height, m.channels(), m.bytes_per_pixel(), m.has_alpha()), (5, 7, 4, 8, true)); + let m = pixel_model(&png_with(4, 3, &[])).unwrap(); + assert_eq!((m.bytes_per_pixel(), m.has_alpha()), (3, false)); + } + + #[test] + fn pixel_model_skips_a_huge_iccp_without_inflating() { + let junk = vec![0xAB; 20 << 20]; + let bytes = png_with(8, 2, &[(b"iCCP", junk), (b"tRNS", vec![0; 6])]); + assert_eq!(tuple(&bytes), oracle(&bytes)); + assert_eq!(tuple(&bytes), Some((5, 7, 4, true))); + } + + #[test] + fn pixel_model_malformed_inputs_agree_with_oracle_and_never_panic() { + let full = png_with(8, 6, &[(b"tRNS", vec![0]), (b"gAMA", vec![0; 4])]); + for n in 0..=full.len() { + let cut = &full[..n]; + let got = tuple(cut); + // an Err where the oracle answers can only be a stricter header check + if got.is_some() { + assert_eq!(got, oracle(cut), "prefix {n}"); + } + } + assert!(pixel_model(&full[..33]).is_err()); + // missing IHDR + let mut bad = full.clone(); + bad[12..16].copy_from_slice(b"IHDX"); + assert!(pixel_model(&bad).is_err() && oracle(&bad).is_none()); + // chunk length overflow: a length past the input, then one past i32::MAX + for len in [u32::MAX, i32::MAX as u32, 0x7fff_fff0] { + let mut o = full.clone(); + o[33..37].copy_from_slice(&len.to_be_bytes()); + assert!(pixel_model(&o).is_err(), "len {len:#x}"); + assert_eq!(tuple(&o), oracle(&o)); + } + // IEND before IDAT, unknown colour type, zero size, bad signature + let mut iend = png_with(8, 2, &[]); + let at = iend.windows(4).position(|w| w == b"IDAT").unwrap(); + iend[at..at + 4].copy_from_slice(b"IEND"); + assert!(pixel_model(&iend).is_err() && oracle(&iend).is_none()); + assert!(pixel_model(&png_with(8, 5, &[])).is_err()); + let mut zero = png_with(8, 2, &[]); + zero[16..20].copy_from_slice(&0u32.to_be_bytes()); + assert!(pixel_model(&zero).is_err()); + assert!(pixel_model(b"not a png").is_err()); + // deterministic pseudo-random corruption + let mut s = 0x9e37_79b9u32; + for _ in 0..2000 { + let mut f = full.clone(); + for _ in 0..3 { + s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let i = (s >> 8) as usize % f.len(); + f[i] = (s >> 24) as u8; + } + let _ = pixel_model(&f); + } + } + + #[test] + fn pixel_model_many_tiny_chunks_and_the_chunk_cap() { + let many: Vec<(&[u8; 4], Vec)> = (0..10_000).map(|_| (b"tEXt", Vec::new())).chain([(b"tRNS", vec![0])]).collect(); + let bytes = png_with(8, 0, &many); + assert_eq!(tuple(&bytes), oracle(&bytes)); + assert_eq!(tuple(&bytes), Some((5, 7, 2, true))); + let over: Vec<(&[u8; 4], Vec)> = (0..MAX_PROBE_CHUNKS + 1).map(|_| (b"tEXt", Vec::new())).collect(); + assert!(matches!(pixel_model(&png_with(8, 0, &over)), Err(CodecError::LimitExceeded(_)))); + } } diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 4a31def00..1c22411dc 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -32,6 +32,25 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { Ok((w, h, orientation)) } +/// Whether a WebP carries transparency, from the first chunk only (nothing is decoded): +/// `VP8X` flag bit 0x10, `VP8L` `alpha_is_used`, plain `VP8` never. +pub fn has_alpha(bytes: &[u8]) -> Result { + let err = |s: &str| CodecError::malformed(Format::WebP, s); + if bytes.get(..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WEBP") { + return Err(err("bad signature")); + } + match bytes.get(12..16) { + Some(b"VP8X") => Ok(bytes.get(20).ok_or_else(|| err("truncated VP8X"))? & 0x10 != 0), + // 0x2f signature byte, then 14+14 size bits, then the alpha_is_used bit (bit 28) + Some(b"VP8L") => match bytes.get(20..25) { + Some([0x2f, a, b, c, d]) => Ok(u32::from_le_bytes([*a, *b, *c, *d]) >> 28 & 1 != 0), + _ => Err(err("bad VP8L header")), + }, + Some(b"VP8 ") => Ok(false), + _ => Err(err("no image data")), + } +} + #[cfg(test)] mod tests { use super::*; @@ -71,4 +90,39 @@ mod tests { bytes.push(0); assert!(header(&bytes).is_err()); } + + #[test] + fn has_alpha_reads_vp8x_vp8l_and_plain_vp8() { + for (layout, want) in [(crate::ChannelLayout::Rgb, false), (crate::ChannelLayout::Rgba, true)] { + let n = layout.channels(); + let image = crate::Image::from_u8(2, 3, layout, vec![42; 6 * n]).unwrap(); + let bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + assert_eq!(has_alpha(&bytes).unwrap(), want); + } + let riff = |chunk: &[u8; 4], body: &[u8]| { + let mut v = b"RIFF\0\0\0\0WEBP".to_vec(); + v.extend_from_slice(chunk); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v + }; + let mut x = [0u8; 10]; + assert!(!has_alpha(&riff(b"VP8X", &x)).unwrap()); + x[0] = 0x10; + assert!(has_alpha(&riff(b"VP8X", &x)).unwrap()); + assert!(!has_alpha(&riff(b"VP8 ", &[0; 10])).unwrap()); + assert!(has_alpha(&riff(b"VP8L", &[0x2f, 0, 0, 0, 0x10])).unwrap()); + assert!(!has_alpha(&riff(b"VP8L", &[0x2f, 0, 0, 0, 0])).unwrap()); + } + + #[test] + fn has_alpha_rejects_malformed_prefixes() { + let full = [b"RIFF\0\0\0\0WEBPVP8X\x0a\0\0\0".as_slice(), &[0x10; 10]].concat(); + for n in 0..20 { + assert!(has_alpha(&full[..n]).is_err(), "prefix {n}"); + } + assert!(has_alpha(&full[..21]).is_ok()); + assert!(has_alpha(b"RIFF\0\0\0\0WEBPVP8L\x05\0\0\0\x2e").is_err()); + assert!(has_alpha(b"junk").is_err()); + } } From 38289b53430f72815ffa3bdcdcc8d4a537fee7ae Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:45:56 +0100 Subject: [PATCH 003/311] craft-image-codecs: wrap a clipboard DIB as a BMP (dib_to_bmp, dib_layout) (#2062) * image-codecs: wrap a clipboard DIB as a BMP (#778) Add bmp_probe::dib_to_bmp (prepend the 14-byte file header, pixel offset from the header with saturating arithmetic, try_reserve for the output) and bmp_probe::dib_layout (V4/V5 alpha-mask BI_RGB becomes BI_BITFIELDS, mask copy after the header). Both are ported from WordCraft's crates/geom/src/picture.rs so it can drop its local copies. Tests compare byte-for-byte with the originals over crafted DIBs and every prefix, and decode wrapped results. Co-Authored-By: Claude Opus 5.5 * image-codecs: fix DIB offsets for V2/V3 bitfields and ambiguous mask copies (#778) - dib_to_bmp no longer adds 12 appended-mask bytes to the pixel offset for 52- and 56-byte BI_BITFIELDS headers, which carry their masks inside the header; the decoder reads the pixels at bfOffBits, so the offset was 12 bytes too far. - dib_layout treats 12 bytes after the header that equal the masks as an existing copy only when more bytes follow than the pixels need, so an exact-length DIB whose pixels equal the masks gets its copy inserted. - dib_layout reserves the 12 bytes before changing compression or masks, so a failed reservation returns the DIB unchanged; the mask bytes are a [u8; 12] array, not a heap copy. The differential tests against the WordCraft originals now exclude exactly the 52/56-byte bitfields offset and the exact-length payload cases, and assert the new behaviour for them. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 93dac78c93a7f1fd66e2022edeb089233b1dc45a) --- crates/image-codecs/src/bmp_probe.rs | 442 +++++++++++++++++++++++++++ 1 file changed, 442 insertions(+) diff --git a/crates/image-codecs/src/bmp_probe.rs b/crates/image-codecs/src/bmp_probe.rs index 5b47721bc..89f6a3b97 100644 --- a/crates/image-codecs/src/bmp_probe.rs +++ b/crates/image-codecs/src/bmp_probe.rs @@ -1,5 +1,7 @@ //! Header-only BMP dimensions and pixel-data coverage, without allocating a canvas. +use crate::error::CodecError; + /// Recognize a BMP file header with a supported DIB header kind. /// /// This is a format-routing check, not full validation: dimensions and pixel data may still @@ -13,6 +15,115 @@ pub fn is_supported_header(b: &[u8]) -> bool { false } +/// Wrap a DIB (a BMP without its 14-byte `BITMAPFILEHEADER`, as the Windows clipboard holds one +/// for `CF_DIB` and `CF_DIBV5`) as a BMP file the decoders here read. The pixel offset is computed +/// from the header with saturating arithmetic, so a hostile header cannot overflow; whether the +/// pixel data exists is left to the decoder. Apply [`dib_layout`] first for clipboard DIBs. +/// +/// # Errors +/// +/// Returns [`CodecError::LimitExceeded`] when the output (`dib.len() + 14` bytes) cannot be allocated. +pub fn dib_to_bmp(dib: &[u8]) -> Result, CodecError> { + let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let bi_size = u32_at(0).unwrap_or(40); + let offset = if bi_size == 12 { + let bpp = u16_at(10).unwrap_or(24); + let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; + 14 + bi_size + palette + } else { + let bpp = u16_at(14).unwrap_or(24); + let compression = u32_at(16).unwrap_or(0); + let clr_used = u32_at(32).unwrap_or(0); + let palette_entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + // The masks of a 52- or 56-byte (V2/V3) header are inside the header; only the other + // header kinds carry them as 12 further bytes before the pixels. + let masks = if compression == 3 && bi_size >= 40 && !matches!(bi_size, 52 | 56) { 12 } else { 0 }; + 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) + }; + let total = dib.len().saturating_add(14); + let file_size = u32::try_from(total).unwrap_or(u32::MAX); + let mut bmp = Vec::new(); + bmp.try_reserve_exact(total).map_err(|_| CodecError::LimitExceeded(format!("a {total}-byte BMP")))?; + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&file_size.to_le_bytes()); + bmp.extend_from_slice(&[0u8; 4]); + bmp.extend_from_slice(&offset.to_le_bytes()); + bmp.extend_from_slice(dib); + Ok(bmp) +} + +/// Put a clipboard DIB with a V4 or V5 header (108 bytes or more) in the layout the decoder reads. +/// A 32-bit one whose alpha mask is set but whose compression says `BI_RGB` is marked +/// `BI_BITFIELDS` (with the usual colour masks when it gives none), so its alpha is kept as +/// Windows programs mean it; arboard makes the same change. Bit fields then need the colour masks +/// after the header too, where Windows puts a copy and the decoder skips them; a DIB without that +/// copy gets it. Any other DIB comes back unchanged, as does one whose 12 extra bytes cannot be +/// allocated. +pub fn dib_layout(mut dib: Vec) -> Vec { + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; + let put = |d: &mut Vec, at: usize, v: u32| { + if let Some(b) = d.get_mut(at..at + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + }; + // Decide everything first and mutate only after the 12-byte reservation succeeded, so a failed + // allocation returns the DIB unchanged. + let promote = dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000); + let default_masks = promote && (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)); + let mut masks = dib.get(40..52).and_then(|b| <[u8; 12]>::try_from(b).ok()); + if default_masks { + let mut m = [0u8; 12]; + m[0..4].copy_from_slice(&0x00FF_0000u32.to_le_bytes()); + m[4..8].copy_from_slice(&0x0000_FF00u32.to_le_bytes()); + m[8..12].copy_from_slice(&0x0000_00FFu32.to_le_bytes()); + masks = Some(m); + } + let bitfields = promote || u32_at(&dib, 16) == Some(3); + // Bytes equal to the masks right after the header are a copy only when more bytes follow than + // the pixels need; otherwise they are the pixels (e.g. a 3x1 V5 DIB with pixels equal to the masks). + let has_copy = |m: &[u8; 12]| { + dib.get(size..size.saturating_add(12)) == Some(m.as_slice()) && pixel_bytes(&dib).is_none_or(|need| dib.len().saturating_sub(size) > need) + }; + let insert = match masks { + Some(m) if bitfields && size <= dib.len() && !has_copy(&m) => Some(m), + _ => None, + }; + if insert.is_some() && dib.try_reserve(12).is_err() { + return dib; + } + if promote { + put(&mut dib, 16, 3); + if default_masks { + put(&mut dib, 40, 0x00FF_0000); + put(&mut dib, 44, 0x0000_FF00); + put(&mut dib, 48, 0x0000_00FF); + } + } + if let Some(m) = insert { + dib.splice(size..size, m); + } + dib +} + +/// Bytes of pixel rows (4-byte aligned stride) the info-header dimensions of `dib` call for, or +/// `None` when width, height or bit count cannot be read. +fn pixel_bytes(dib: &[u8]) -> Option { + let i32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes); + let w = u64::try_from(i32_at(4)?).ok()?; + let h = u64::from(i32_at(8)?.unsigned_abs()); + let bpp = u64::from(u16::from_le_bytes(dib.get(14..16)?.try_into().ok()?)); + let stride = w.checked_mul(bpp)?.div_ceil(32).checked_mul(4)?; + usize::try_from(stride.checked_mul(h)?).ok() +} + /// Coverage of the declared pixel array. Row byte counts include row padding; RLE coverage /// counts the pixels drawn by commands and may be smaller than the canvas. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -174,4 +285,335 @@ mod tests { b[0] = b'X'; assert!(!is_supported_header(&b)); } + + // The WordCraft originals, kept verbatim as the oracle. + fn oracle_dib_to_bmp(dib: &[u8]) -> Vec { + let u16_at = |at: usize| dib.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); + let u32_at = |at: usize| dib.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let bi_size = u32_at(0).unwrap_or(40); + let offset = if bi_size == 12 { + let bpp = u16_at(10).unwrap_or(24); + let palette = if bpp <= 8 { (1u32 << bpp) * 3 } else { 0 }; + 14 + bi_size + palette + } else { + let bpp = u16_at(14).unwrap_or(24); + let compression = u32_at(16).unwrap_or(0); + let clr_used = u32_at(32).unwrap_or(0); + let palette_entries = if clr_used != 0 { + clr_used + } else if bpp <= 8 { + 1u32 << bpp + } else { + 0 + }; + let masks = if compression == 3 && bi_size >= 40 { 12 } else { 0 }; + 14u32.saturating_add(bi_size).saturating_add(masks).saturating_add(palette_entries.saturating_mul(4)) + }; + let file_size = u32::try_from(14 + dib.len()).unwrap_or(u32::MAX); + let mut bmp = Vec::with_capacity(14 + dib.len()); + bmp.extend_from_slice(b"BM"); + bmp.extend_from_slice(&file_size.to_le_bytes()); + bmp.extend_from_slice(&[0u8; 4]); + bmp.extend_from_slice(&offset.to_le_bytes()); + bmp.extend_from_slice(dib); + bmp + } + + fn oracle_dib_layout(mut dib: Vec) -> Vec { + let u32_at = |d: &[u8], at: usize| d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes); + let Some(size) = u32_at(&dib, 0).filter(|&s| s >= 108).and_then(|s| usize::try_from(s).ok()) else { return dib }; + let put = |d: &mut Vec, at: usize, v: u32| { + if let Some(b) = d.get_mut(at..at + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + }; + if dib.get(14..16) == Some(&[32, 0]) && u32_at(&dib, 16) == Some(0) && u32_at(&dib, 52) == Some(0xFF00_0000) { + put(&mut dib, 16, 3); + if (40..52).step_by(4).all(|at| u32_at(&dib, at) == Some(0)) { + put(&mut dib, 40, 0x00FF_0000); + put(&mut dib, 44, 0x0000_FF00); + put(&mut dib, 48, 0x0000_00FF); + } + } + if u32_at(&dib, 16) == Some(3) + && size <= dib.len() + && let Some(masks) = dib.get(40..52).map(<[u8]>::to_vec) + && dib.get(size..size + 12) != Some(masks.as_slice()) + { + dib.splice(size..size, masks); + } + dib + } + + fn core(bpp: u16) -> Vec { + let mut d = Vec::new(); + d.extend_from_slice(&12u32.to_le_bytes()); + d.extend_from_slice(&2u16.to_le_bytes()); + d.extend_from_slice(&2u16.to_le_bytes()); + d.extend_from_slice(&1u16.to_le_bytes()); + d.extend_from_slice(&bpp.to_le_bytes()); + d.resize(12 + 64, 7); + d + } + + #[allow(clippy::too_many_arguments)] + fn info(size: u32, bpp: u16, comp: u32, clr_used: u32, masks: [u32; 4], tail: usize) -> Vec { + let mut d = vec![0u8; size.clamp(40, 124) as usize]; + d[0..4].copy_from_slice(&size.to_le_bytes()); + d[4..8].copy_from_slice(&2i32.to_le_bytes()); + d[8..12].copy_from_slice(&2i32.to_le_bytes()); + d[12..14].copy_from_slice(&1u16.to_le_bytes()); + d[14..16].copy_from_slice(&bpp.to_le_bytes()); + d[16..20].copy_from_slice(&comp.to_le_bytes()); + d[32..36].copy_from_slice(&clr_used.to_le_bytes()); + for (i, m) in masks.iter().enumerate() { + if let Some(b) = d.get_mut(40 + 4 * i..44 + 4 * i) { + b.copy_from_slice(&m.to_le_bytes()); + } + } + d.extend((0..tail).map(|i| (i * 31 + 5) as u8)); + d + } + + fn corpus() -> Vec> { + let mut v = Vec::new(); + for bpp in [1, 4, 8, 24, 0, 99] { + v.push(core(bpp)); + } + for bpp in [1u16, 4, 8, 16, 24, 32, 0, 255] { + for clr in [0u32, 1, 5, 256, u32::MAX] { + v.push(info(40, bpp, 0, clr, [0; 4], 40)); + } + } + for (size, comp, masks) in [ + (40, 3, [0xFF0000, 0xFF00, 0xFF, 0]), + (40, 3, [0; 4]), + (52, 3, [0xFF0000, 0xFF00, 0xFF, 0]), + (108, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (108, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (108, 0, [0, 0, 0, 0xFF00_0000]), + (108, 0, [0; 4]), + (124, 3, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000]), + (124, 0, [0, 0, 0, 0xFF00_0000]), + (124, 0, [1, 0, 0, 0xFF00_0000]), + (124, 0, [0xFF0000, 0xFF00, 0xFF, 0]), + (124, 1, [0, 0, 0, 0xFF00_0000]), + (124, 3, [1, 2, 3, 4]), + (0, 0, [0; 4]), + (12, 0, [0; 4]), + (u32::MAX, 3, [0; 4]), + (u32::MAX, 0, [0; 4]), + (200, 3, [9; 4]), + ] { + for bpp in [8u16, 16, 32] { + for clr in [0u32, 2, u32::MAX] { + v.push(info(size, bpp, comp, clr, masks, 48)); + } + } + } + // 52/56-byte bitfields headers with and without a pixel tail, and 3x1 V5 DIBs. + for size in [52, 56] { + v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 4)); + v.push(info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0)); + } + v.push(v5_3x1(false)); + v.push(v5_3x1(true)); + v + } + + /// 3x1 32-bit V5 BI_BITFIELDS whose three pixels equal the colour masks; with `copy` the DIB + /// also holds the real 12-byte mask copy before the pixels. + fn v5_3x1(copy: bool) -> Vec { + let masks = [0x00FF_0000u32, 0x0000_FF00, 0x0000_00FF]; + let mut d = info(124, 32, 3, 0, [masks[0], masks[1], masks[2], 0xFF00_0000], 0); + d[4..8].copy_from_slice(&3i32.to_le_bytes()); + d[8..12].copy_from_slice(&1i32.to_le_bytes()); + for _ in 0..usize::from(copy) + 1 { + for m in masks { + d.extend_from_slice(&m.to_le_bytes()); + } + } + d + } + + fn dib_u32(d: &[u8], at: usize) -> Option { + d.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes) + } + + /// Fixed case 1: a 52- or 56-byte BI_BITFIELDS header holds its masks itself, so `dib_to_bmp` + /// no longer adds the 12 appended-mask bytes the WordCraft original added to the pixel offset. + fn bmp_offset_fixed(dib: &[u8]) -> bool { + matches!(dib_u32(dib, 0).unwrap_or(40), 52 | 56) && dib_u32(dib, 16) == Some(3) + } + + /// Fixed case 2: the original read 12 pixel bytes equal to the masks (exact-length payload) as a + /// mask copy and inserted nothing. Returns the corrected output when `cut` is such a case. + fn exact_length_fixed(cut: &[u8]) -> Option> { + let o = oracle_dib_layout(cut.to_vec()); + let size = usize::try_from(dib_u32(&o, 0).filter(|&s| s >= 108)?).ok()?; + let need = pixel_bytes(&o)?; + let same = o.len() == cut.len() + && dib_u32(&o, 16) == Some(3) + && size <= o.len() + && o.get(size..size + 12).is_some() + && o.get(size..size + 12) == o.get(40..52) + && o.len() - size <= need; + if !same { + return None; + } + let mut want = o.clone(); + want.splice(size..size, o[40..52].to_vec()); + Some(want) + } + + #[test] + fn dib_helpers_match_the_wordcraft_originals_byte_for_byte() { + let (mut total, mut offset_cases, mut exact_cases) = (0usize, 0usize, 0usize); + for dib in corpus() { + for n in 0..=dib.len() { + let cut = &dib[..n]; + total += 1; + let fixed_layout = exact_length_fixed(cut); + match &fixed_layout { + Some(want) => { + exact_cases += 1; + assert_eq!(&dib_layout(cut.to_vec()), want, "exact-length layout len {n}"); + } + None => assert_eq!(dib_layout(cut.to_vec()), oracle_dib_layout(cut.to_vec()), "layout len {n}"), + } + if bmp_offset_fixed(cut) { + offset_cases += 1; + let (new, old) = (dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut)); + assert_eq!(new[..10], old[..10]); + assert_eq!(new[14..], old[14..]); + let (a, b) = (dib_u32(&new, 10).unwrap(), dib_u32(&old, 10).unwrap()); + assert_eq!(a.saturating_add(12), b, "offset len {n}"); + } else { + assert_eq!(dib_to_bmp(cut).unwrap(), oracle_dib_to_bmp(cut), "bmp len {n}"); + } + let both = dib_layout(cut.to_vec()); + let old_both = oracle_dib_layout(cut.to_vec()); + if fixed_layout.is_none() && !bmp_offset_fixed(&both) { + assert_eq!(dib_to_bmp(&both).unwrap(), oracle_dib_to_bmp(&old_both)); + } + } + } + eprintln!("corpus cases {total}: 52/56-byte bitfields offset {offset_cases}, exact-length payload {exact_cases}"); + assert!(offset_cases > 0 && exact_cases > 0); + } + + #[test] + fn dib_helpers_survive_pseudo_random_bytes() { + let mut x = 0x9E37_79B9_7F4A_7C15u64; + for len in 0..300usize { + let d: Vec = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect(); + let laid = dib_layout(d.clone()); + if exact_length_fixed(&d).is_none() && !bmp_offset_fixed(&laid) { + assert_eq!(dib_to_bmp(&laid).unwrap(), oracle_dib_to_bmp(&oracle_dib_layout(d))); + } + } + } + + #[test] + fn huge_palette_count_saturates_the_offset() { + let b = dib_to_bmp(&info(40, 8, 0, u32::MAX, [0; 4], 8)).unwrap(); + assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX); + let b = dib_to_bmp(&info(u32::MAX, 8, 3, u32::MAX, [0; 4], 8)).unwrap(); + assert_eq!(u32::from_le_bytes([b[10], b[11], b[12], b[13]]), u32::MAX); + } + + #[test] + fn wrapped_dibs_decode_and_keep_alpha() { + // 2x2 32-bit V5, BI_RGB with an alpha mask, bottom-up BGRA pixels. + let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 0); + let px = [[1u8, 2, 3, 255], [4, 5, 6, 128], [7, 8, 9, 64], [10, 11, 12, 0]]; + for p in px { + d.extend_from_slice(&p); + } + let bmp = dib_to_bmp(&dib_layout(d)).unwrap(); + let img = crate::decode(&bmp).unwrap(); + let alphas: Vec = img.to_rgba8().chunks(4).map(|p| u16::from(p[3])).collect(); + assert_eq!(alphas, [64, 0, 255, 128]); + // 24-bit plain DIB and a 12-byte core 8-bit one open too. + let mut d = info(40, 24, 0, 0, [0; 4], 0); + d.extend_from_slice(&[0, 0, 255, 0, 255, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + assert!(crate::decode(&dib_to_bmp(&d).unwrap()).is_ok()); + let mut c = core(8); + c.truncate(12); + c.extend((0..256 * 3).map(|i| i as u8)); + c.extend_from_slice(&[0, 1, 0, 0, 2, 3, 0, 0]); + assert!(crate::decode(&dib_to_bmp(&c).unwrap()).is_ok()); + } + + /// 1x1 32-bit BI_BITFIELDS DIB, one pixel B=10 G=20 R=30 A=128, with the given header size. + fn one_pixel(size: u32) -> Vec { + let mut d = info(size, 32, 3, 0, [0xFF0000, 0xFF00, 0xFF, 0xFF00_0000], 0); + d[4..8].copy_from_slice(&1i32.to_le_bytes()); + d[8..12].copy_from_slice(&1i32.to_le_bytes()); + if size == 40 { + for m in [0xFF0000u32, 0xFF00, 0xFF] { + d.extend_from_slice(&m.to_le_bytes()); + } + } + d.extend_from_slice(&[10, 20, 30, 128]); + d + } + + #[test] + fn bitfields_pixel_offset_for_each_header_size_decodes() { + for size in [40u32, 52, 56] { + let bmp = dib_to_bmp(&one_pixel(size)).unwrap(); + let off = 14 + size + if size == 40 { 12 } else { 0 }; + assert_eq!(dib_u32(&bmp, 10), Some(off), "offset for {size}"); + let img = crate::decode(&bmp).unwrap_or_else(|e| panic!("{size}-byte header: {e:?}")); + let rgba = img.to_rgba8(); + assert_eq!(&rgba[..3], &[30, 20, 10], "size {size}"); + if size == 56 { + assert_eq!(rgba[3], 128); + } + } + // V5: the header's masks, a copy inserted by `dib_layout`, then the pixel. + let bmp = dib_to_bmp(&dib_layout(one_pixel(124))).unwrap(); + assert_eq!(&crate::decode(&bmp).unwrap().to_rgba8()[..4], &[30, 20, 10, 128]); + } + + #[test] + fn exact_length_pixels_equal_to_the_masks_are_not_a_mask_copy() { + let d = v5_3x1(false); + let laid = dib_layout(d.clone()); + assert_eq!(laid.len(), d.len() + 12); + assert_eq!(laid[124..136], d[40..52]); + assert_eq!(oracle_dib_layout(d).len(), laid.len() - 12, "the original skipped the insertion"); + let img = crate::decode(&dib_to_bmp(&laid).unwrap()).unwrap().to_rgba8(); + assert_eq!(img.len(), 12); + // pixel 0 is 0x00FF0000 (blue 0, green 0, red 255 under the masks). + assert_eq!(&img[..3], &[255, 0, 0]); + // A real copy followed by the pixels is left alone. + let real = v5_3x1(true); + assert_eq!(dib_layout(real.clone()), real); + assert!(crate::decode(&dib_to_bmp(&real).unwrap()).is_ok()); + } + + #[test] + fn layout_decides_before_it_mutates() { + // BI_RGB V5 with an alpha mask and no colour masks: promoted and given a copy together. + let mut d = info(124, 32, 0, 0, [0, 0, 0, 0xFF00_0000], 16); + d[4..8].copy_from_slice(&2i32.to_le_bytes()); + let laid = dib_layout(d.clone()); + assert_eq!(laid.len(), d.len() + 12); + assert_eq!(dib_u32(&laid, 16), Some(3)); + // Unreadable dimensions keep the byte-equality rule. + let mut odd = info(108, 32, 3, 0, [1, 2, 3, 0], 0); + odd[4..8].copy_from_slice(&(-1i32).to_le_bytes()); + let copy = odd[40..52].to_vec(); + odd.extend_from_slice(©); + assert_eq!(dib_layout(odd.clone()), odd); + } } From 20c67ba4f50e6c3013b17c60ad2f714b2eddb545 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:23:25 -0500 Subject: [PATCH 004/311] zip: support bounded aligned stored entry options Co-authored-by: bflatastic (cherry picked from commit e66b3a79549bc951f9ebbd2783c2972401de72d7) --- ATTRIBUTION.md | 4 +++ crates/zip/src/write.rs | 21 ++++++++++++- crates/zip/tests/aligned_writer.rs | 49 ++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 crates/zip/tests/aligned_writer.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c42bc8168..fbb351107 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -128,3 +128,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## Screen Video key frames `crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. + +## Aligned stored ZIP entries + +The USDZ alignment requirement and compatibility fixture for `Writer::add_stored_aligned` come from TextureCraft `crates/formats/src/mesh_export/usd.rs`, introduced by bflatastic in `bdbb52c9` and maintained through `9eb20086` (MIT OR Apache-2.0). The shared API and alignment validation are subsequent Dylan M. Taylor work. Scene/material mapping remains in TextureCraft. diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index e1fdfad9e..6e62c6f20 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -44,6 +44,24 @@ impl Writer { /// 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) + } + + /// Adds a stored entry whose payload starts on an `alignment`-byte boundary. + /// + /// USDZ uses 64. Only powers of two from 1 through 4096 are accepted, bounding + /// per-entry padding. This does not impose a total archive-size budget; callers + /// retain their format-specific size and name policies. Discard the writer after + /// a write error, just as for [`Self::add`]. Invalid alignment is rejected before + /// starting an entry. + pub fn add_stored_aligned(&mut self, name: &str, data: &[u8], alignment: u16) -> Result<(), Error> { + if !alignment.is_power_of_two() || alignment > 4096 { + return Err(Error::Write("alignment must be a power of two between 1 and 4096".into())); + } + self.add_entry(name, data, Compression::Stored, alignment) + } + + fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16) -> Result<(), Error> { let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), @@ -53,7 +71,8 @@ impl Writer { .compression_method(method) .compression_level(level) .last_modified_time(zip::DateTime::default()) - .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2); + .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2) + .with_alignment(alignment); let fail = |e: &dyn std::fmt::Display| Error::Write(format!("{name}: {e}")); self.zip.start_file(name, options).map_err(|e| fail(&e))?; self.zip.write_all(data).map_err(|e| fail(&e)) diff --git a/crates/zip/tests/aligned_writer.rs b/crates/zip/tests/aligned_writer.rs new file mode 100644 index 000000000..03c664e5b --- /dev/null +++ b/crates/zip/tests/aligned_writer.rs @@ -0,0 +1,49 @@ +use craft_zip::{Compression, Writer}; +use std::io::{Cursor, Read, Write}; + +#[test] +fn aligned_stored_matches_previous_usdz_writer() { + for tail in 0..128 { + let payload = vec![37u8; tail]; + let entries: [(&str, &[u8]); 3] = [("scene.usdc", b"PXR-USDC"), ("textures/synthetic.png", &payload), ("empty", b"")]; + let mut shared = Writer::new(); + let mut previous = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); + for (name, data) in entries { + shared.add_stored_aligned(name, data, 64).unwrap(); + previous.start_file(name, options).unwrap(); + previous.write_all(data).unwrap(); + } + let bytes = shared.finish().unwrap(); + assert_eq!(bytes, previous.finish().unwrap().into_inner()); + let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + for (i, (name, expected)) in entries.iter().enumerate() { + let mut file = archive.by_index(i).unwrap(); + assert_eq!(file.name().unwrap(), *name); + assert_eq!(file.compression(), zip::CompressionMethod::Stored); + assert_eq!(file.data_start().unwrap() % 64, 0); + let mut actual = Vec::new(); + file.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, *expected); + } + } +} + +#[test] +fn invalid_alignment_does_not_start_entry_and_duplicates_fail() { + let mut writer = Writer::new(); + for alignment in [0, 3, 65, 8192, u16::MAX] { + assert!(writer.add_stored_aligned("layer", b"data", alignment).is_err()); + } + writer.add_stored_aligned("layer", b"data", 64).unwrap(); + assert!(writer.add_stored_aligned("layer", b"again", 64).is_err()); +} + +#[test] +fn alignment_one_retains_ordinary_stored_bytes() { + let mut ordinary = Writer::new(); + ordinary.add("entry", b"data", Compression::Stored).unwrap(); + let mut aligned = Writer::new(); + aligned.add_stored_aligned("entry", b"data", 1).unwrap(); + assert_eq!(ordinary.finish().unwrap(), aligned.finish().unwrap()); +} From 1ba84bb14aaf45b609dff9a34907ea5836e38115 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:24:27 -0500 Subject: [PATCH 005/311] Keep aligned stored entry headers compatible with USDZ exporter (cherry picked from commit 6128eabbfb98e5fe486fa7ee4413724e2a4ca908) --- crates/zip/src/write.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 6e62c6f20..451729759 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -44,11 +44,13 @@ impl Writer { /// 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) + self.add_entry(name, data, compression, 1, data.len() as u64 >= u64::from(u32::MAX) / 2) } /// Adds a stored entry whose payload starts on an `alignment`-byte boundary. /// + /// Entries use ordinary ZIP headers, matching the USDZ writer this replaces; + /// oversized entries fail rather than opting into ZIP64 headers. /// USDZ uses 64. Only powers of two from 1 through 4096 are accepted, bounding /// per-entry padding. This does not impose a total archive-size budget; callers /// retain their format-specific size and name policies. Discard the writer after @@ -58,10 +60,10 @@ impl Writer { if !alignment.is_power_of_two() || alignment > 4096 { return Err(Error::Write("alignment must be a power of two between 1 and 4096".into())); } - self.add_entry(name, data, Compression::Stored, alignment) + self.add_entry(name, data, Compression::Stored, alignment, false) } - fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16) -> Result<(), Error> { + fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16, large_file: bool) -> Result<(), Error> { let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), @@ -71,7 +73,7 @@ impl Writer { .compression_method(method) .compression_level(level) .last_modified_time(zip::DateTime::default()) - .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2) + .large_file(large_file) .with_alignment(alignment); let fail = |e: &dyn std::fmt::Display| Error::Write(format!("{name}: {e}")); self.zip.start_file(name, options).map_err(|e| fail(&e))?; From 45d9cab53bab64b8851bcac7b5521a732259e511 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 14:14:21 -0500 Subject: [PATCH 006/311] zip: preserve legacy Zstandard method 20 in lenient reads (#2015) * zip: retain legacy Zstandard method compatibility Ported from Craft Anything 29badae7c9280fdf4c24795927bf3a91f51694c6, including the bounded-reader regression. Firmware scanner policy remains app-owned. * Record source of legacy ZIP Zstandard compatibility * Document both ZIP Zstandard method identifiers --------- Co-authored-by: RRFZ <247457381+Plastic-time@users.noreply.github.com> (cherry picked from commit fb1d7f3681d1f13156ca16f502624c254bb5d564) --- ATTRIBUTION.md | 3 +++ crates/zip/Cargo.toml | 2 +- crates/zip/src/lenient.rs | 4 ++-- crates/zip/src/lenient/tests.rs | 37 +++++++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fbb351107..e12acfa77 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -122,9 +122,12 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. +The legacy ZIP Zstandard method-20 mapping and bounded-read regression in `crates/zip/src/lenient` are ported from RRFZ's Craft Anything commit `29badae7c9280fdf4c24795927bf3a91f51694c6` (MIT OR Apache-2.0). RRFZ remains the primary Git author. Firmware scanner detection remains app-owned and is not part of this port. + The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0. Sanitization, animation fitting and numeric output policy remain caller-owned. + ## Screen Video key frames `crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. diff --git a/crates/zip/Cargo.toml b/crates/zip/Cargo.toml index 89cb2d1a7..cfdb333b4 100644 --- a/crates/zip/Cargo.toml +++ b/crates/zip/Cargo.toml @@ -35,7 +35,7 @@ lenient = ["dep:miniz_oxide"] lenient-bzip2 = ["lenient", "dep:bzip2-rs"] # Methods 14 (ZIP LZMA) and 95 (XZ). lenient-lzma = ["lenient", "dep:lzma-rs"] -# Method 93. +# Zstandard methods 20 (legacy) and 93. lenient-zstd = ["lenient", "dep:ruzstd"] serde = ["dep:serde"] diff --git a/crates/zip/src/lenient.rs b/crates/zip/src/lenient.rs index c9bed3764..20da277cd 100644 --- a/crates/zip/src/lenient.rs +++ b/crates/zip/src/lenient.rs @@ -91,7 +91,7 @@ impl ZipEntry { 9 => "deflate64", 12 => "bzip2", 14 => "lzma", - 93 => "zstd", + 20 | 93 => "zstd", 95 => "xz", 99 => "aes", _ => "other", @@ -463,7 +463,7 @@ pub fn read_entry_unverified(data: &[u8], e: &ZipEntry, max_bytes: u64) -> Resul })?, 12 | 95 => decode_bzip2_or_xz(raw, e, max_bytes)?, 14 => decode_lzma(raw, e, max_bytes)?, - 93 => decode_zstd(raw, e, max_bytes)?, + 20 | 93 => decode_zstd(raw, e, max_bytes)?, m => return Err(ZipError::Unsupported(format!("compression method {m} ({}) for {}", e.method_name(), e.name))), }; if out.len() as u64 != e.uncompressed_size { diff --git a/crates/zip/src/lenient/tests.rs b/crates/zip/src/lenient/tests.rs index c2ca97394..ded7c0ecd 100644 --- a/crates/zip/src/lenient/tests.rs +++ b/crates/zip/src/lenient/tests.rs @@ -391,3 +391,40 @@ fn a_method_left_out_of_the_build_is_unsupported() { data[8..10].copy_from_slice(&93u16.to_le_bytes()); assert!(matches!(read_entry_unverified(&data, &entry, 100), Err(ZipError::Unsupported(m)) if m.contains("not built in"))); } + +// RRFZ, Craft Anything 29badae7: deprecated ZIP method 20 is Zstandard. +#[cfg(feature = "lenient-zstd")] +mod legacy_zstandard { + use crate::lenient as zip; + use crate::lenient::testkit::zip_stored; + + const BODY: &[u8] = b"zstandard payload"; + + /// Build a ZIP with one single-segment Zstandard frame containing a raw final block. + fn sample(method: u16) -> Vec { + let size = BODY.len() as u8; + let mut frame = vec![0x28, 0xb5, 0x2f, 0xfd, 0x20, size, (size << 3) | 1, 0, 0]; + frame.extend_from_slice(BODY); + let mut data = zip_stored(&[("a.txt", &frame)]); + let cd = 30 + "a.txt".len() + frame.len(); + data[8..10].copy_from_slice(&method.to_le_bytes()); + data[14..18].copy_from_slice(&zip::crc32(BODY).to_le_bytes()); + data[22..26].copy_from_slice(&u32::from(size).to_le_bytes()); + data[cd + 10..cd + 12].copy_from_slice(&method.to_le_bytes()); + data[cd + 16..cd + 20].copy_from_slice(&zip::crc32(BODY).to_le_bytes()); + data[cd + 24..cd + 28].copy_from_slice(&u32::from(size).to_le_bytes()); + data + } + + /// The deprecated and current method IDs both decode through the bounded ZIP reader. + #[test] + fn reads_zstandard_members_under_both_method_ids() { + for method in [93, 20] { + let data = sample(method); + let entry = zip::parse(&data, 1).unwrap().entries.remove(0); + assert_eq!(entry.method_name(), "zstd", "method {method}"); + assert_eq!(zip::read_entry(&data, &entry, 100).unwrap(), BODY); + assert!(matches!(zip::read_entry(&data, &entry, 2), Err(zip::ZipError::TooLarge(2)))); + } + } +} From 1d8bfe6acd5808ddcb90bd687d309534517c8636 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 11:30:24 -0500 Subject: [PATCH 007/311] drawingml: accept borrowed table definitions and caller XML validation (#2045) (cherry picked from commit cff5af869dbf6926801c9ac63a927d155202ba3b) --- crates/drawingml/src/table/styles.rs | 63 +++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/drawingml/src/table/styles.rs b/crates/drawingml/src/table/styles.rs index cae3e0dd8..9be968088 100644 --- a/crates/drawingml/src/table/styles.rs +++ b/crates/drawingml/src/table/styles.rs @@ -211,6 +211,26 @@ fn style_def(w: &mut Writer, id: &str, name: &str) { /// opened file defined (`defs`), written back as they were read. A generated style is named /// `"{name_prefix} {label}"` (`"Acme Medium 2 Accent 1"`). pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], name_prefix: &str) -> Vec { + table_styles_xml_with(used, defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())), name_prefix, |raw| { + crate::xmlx::parse(raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) + }) +} + +/// Write table style definitions without copying a caller's model or raw XML. +/// +/// `defs` yields `(id, raw_xml)` in file order and must replay the same sequence when cloned. +/// `valid` retains the caller's bounded XML-admission policy; accepted fragments are emitted +/// verbatim. It must reject fragments the caller cannot safely preserve. The ordinary +/// [`table_styles_xml`] API continues to use this crate's bounded parser. +/// +/// Input/output budgets remain caller-owned. Duplicate selection, case handling, and validation +/// order match [`table_styles_xml`]; invalid first definitions do not fall through to later ones. +pub fn table_styles_xml_with<'a>( + used: &[String], + defs: impl Iterator + Clone, + name_prefix: &str, + mut valid: impl FnMut(&str) -> bool, +) -> Vec { let mut w = Writer::document(); w.tag("a:tblStyleLst").attr("xmlns:a", NS_A).attr("def", "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}").open(); let names = crate::table::table_styles(); @@ -218,19 +238,19 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n // definitions by lower-case id (the first wins). let mut done: std::collections::HashSet<&str> = std::collections::HashSet::new(); let mut done_lower: std::collections::HashSet = std::collections::HashSet::new(); - let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); - for d in defs { - def_of.entry(d.id.to_ascii_lowercase()).or_insert(d); + let mut def_of: std::collections::HashMap = std::collections::HashMap::new(); + for (id, raw) in defs.clone() { + def_of.entry(id.to_ascii_lowercase()).or_insert(raw); } for s in used { if !done.insert(s.as_str()) { continue; } done_lower.insert(s.to_ascii_lowercase()); - if let Some(d) = def_of.get(&s.to_ascii_lowercase()) - && crate::xmlx::parse(d.raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) + if let Some(raw) = def_of.get(&s.to_ascii_lowercase()) + && valid(raw) { - w.raw(&d.raw); + w.raw(raw); continue; } let (_, define) = guid_for_style(s); @@ -241,13 +261,13 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n style_def(&mut w, s, &name); } // Styles the file defined but no table uses still belong to the deck. - for d in defs { - if done_lower.contains(&d.id.to_ascii_lowercase()) { + for (id, raw) in defs { + if done_lower.contains(&id.to_ascii_lowercase()) { continue; } - if crate::xmlx::parse(d.raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) { - done_lower.insert(d.id.to_ascii_lowercase()); - w.raw(&d.raw); + if valid(raw) { + done_lower.insert(id.to_ascii_lowercase()); + w.raw(raw); } } w.close(); @@ -258,6 +278,27 @@ pub fn table_styles_xml(used: &[String], defs: &[crate::table::TableStyleDef], n mod tests { use super::*; + #[test] + fn borrowed_writer_preserves_model_api_and_validation_order() { + let defs = [ + crate::table::TableStyleDef { id: "custom".into(), raw: "".into(), ..Default::default() }, + crate::table::TableStyleDef { id: "CUSTOM".into(), raw: "".into(), ..Default::default() }, + ]; + let used = vec!["custom".into(), "custom".into(), "light1-accent1".into()]; + let borrowed = || defs.iter().map(|d| (d.id.as_str(), d.raw.as_str())); + assert_eq!( + table_styles_xml(&used, &defs, "App"), + table_styles_xml_with(&used, borrowed(), "App", |raw| { crate::xmlx::parse(raw.as_bytes()).is_ok_and(|x| x.is(Local("tblStyle"))) }) + ); + let mut checked = Vec::new(); + let bytes = table_styles_xml_with(&used, borrowed(), "App", |raw| { + checked.push(raw.to_owned()); + false + }); + assert_eq!(checked, [""]); + assert!(!String::from_utf8(bytes).unwrap().contains("duplicate=")); + } + #[test] fn style_parts_follow_schema_order() { const ORDER: [&str; 14] = [ From cbc63d92c19178922959c954c611e453ced904eb Mon Sep 17 00:00:00 2001 From: Martin Ball <98639962+benandez@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:45:52 +0100 Subject: [PATCH 008/311] craft-mcp-server: options for apps that report argument errors as tool results (#2061) * craft-mcp-server: options for apps that report argument errors as tool results (#778) Add `Options` (default = today's behaviour) and `Server::with_options`: - `website_url`: sent as `serverInfo.websiteUrl` at `initialize`. - `tool_errors_as_results`: a `tools/call` whose arguments fail the schema check, or whose tool is unknown, returns a tool result with `isError: true` and the message as text, not -32602. - `strict_request_ids`: a request id that is not a string or number gets -32600 with a null id. `Info` is unchanged, so existing struct-literal callers still compile. Tests cover each option on and off, and hostile input with all options on. Co-Authored-By: Claude Opus 5.5 * craft-mcp-server: strict request ids also apply to the missing-method error (#778) With strict_request_ids, a message without `method` echoed an object, array or bool id in its -32600 reply. It now answers with a null id for any id that is not a string or number, as the later strict check does. Valid ids, absent ids and incoming responses behave as before. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 3e82d1719cb0c6a5e0e4978a73d6893072c2ce17) --- crates/mcp-server/src/lib.rs | 2 +- crates/mcp-server/src/server.rs | 45 +++++++++-- crates/mcp-server/src/tests.rs | 131 +++++++++++++++++++++++++++++++- 3 files changed, 171 insertions(+), 7 deletions(-) diff --git a/crates/mcp-server/src/lib.rs b/crates/mcp-server/src/lib.rs index 17e6827c4..66568fc05 100644 --- a/crates/mcp-server/src/lib.rs +++ b/crates/mcp-server/src/lib.rs @@ -15,7 +15,7 @@ mod server; pub use content::{Contents, base64, image_result, text_result}; pub use schema::{Effect, check_arguments, object, string, tool}; -pub use server::{Incoming, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; +pub use server::{Incoming, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, read_message, response}; #[cfg(test)] mod tests; diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs index b7ed05027..e0d064da5 100644 --- a/crates/mcp-server/src/server.rs +++ b/crates/mcp-server/src/server.rs @@ -4,7 +4,7 @@ use std::io::{BufRead, Write}; use serde_json::{Value, json}; -use crate::content::Contents; +use crate::content::{Contents, text_result}; use crate::schema::{check_arguments, check_prompt_arguments}; /// The newest protocol revision we speak; offered when the client asks for one we don't know. @@ -88,9 +88,25 @@ pub struct Info { pub max_line: usize, } +/// Opt-in behaviour for apps with their own conventions; `Options::default()` is what [`Server::new`] +/// does. Set with [`Server::with_options`]. +#[derive(Clone, Debug, Default)] +pub struct Options { + /// Sent as `serverInfo.websiteUrl` at `initialize` (MCP 2025-06-18) when set. + pub website_url: Option, + /// Report a `tools/call` whose arguments fail the check against the tool's schema, or whose + /// tool is unknown, as a tool result with `isError: true` and the message as text, not as a + /// JSON-RPC -32602 error. For apps whose clients read every tool failure from the result. + pub tool_errors_as_results: bool, + /// Refuse a request whose `id` is neither a string nor a number (JSON-RPC 2.0) with -32600 and + /// a null id, instead of echoing the id back. + pub strict_request_ids: bool, +} + /// An MCP server over the app's [`Tools`]. pub struct Server { info: Info, + options: Options, tools: T, initialized: bool, } @@ -157,7 +173,13 @@ pub fn response(id: Value, result: Value) -> Value { impl Server { pub fn new(info: Info, tools: T) -> Self { - Self { info, tools, initialized: false } + Self { info, options: Options::default(), tools, initialized: false } + } + /// This server with `options` ([`Options`]) in place of the defaults. + #[must_use] + pub fn with_options(mut self, options: Options) -> Self { + self.options = options; + self } pub fn tools(&mut self) -> &mut T { &mut self.tools @@ -215,7 +237,11 @@ impl Server { if o.contains_key("result") || o.contains_key("error") { return None; } - return Some(error(id.unwrap_or(Value::Null), INVALID_REQUEST, "missing `method`")); + let echoed = match id { + Some(id) if !self.options.strict_request_ids || id.is_string() || id.is_number() => id, + _ => Value::Null, + }; + return Some(error(echoed, INVALID_REQUEST, "missing `method`")); }; let params = o.get("params").cloned().unwrap_or(Value::Null); let Some(id) = id else { @@ -224,6 +250,9 @@ impl Server { } return None; }; + if self.options.strict_request_ids && !(id.is_string() || id.is_number()) { + return Some(error(Value::Null, INVALID_REQUEST, "`id` must be a string or number")); + } Some(match self.request(method, ¶ms) { Ok(r) => response(id, r), Err((code, m)) => error(id, code, m), @@ -236,10 +265,14 @@ impl Server { let asked = params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL_VERSION); let version = if SUPPORTED_VERSIONS.contains(&asked) { asked } else { PROTOCOL_VERSION }; let Info { name, title, version: server_version, .. } = self.info; + let mut server_info = json!({"name": name, "title": title, "version": server_version}); + if let Some(url) = &self.options.website_url { + server_info["websiteUrl"] = json!(url); + } Ok(json!({ "protocolVersion": version, "capabilities": self.capabilities(), - "serverInfo": {"name": name, "title": title, "version": server_version}, + "serverInfo": server_info, "instructions": self.tools.instructions(), })) } @@ -251,7 +284,9 @@ impl Server { None | Some(Value::Null) => json!({}), Some(a) => a.clone(), }; - check_arguments(&self.tools.list(), name, &args).map_err(|e| (INVALID_PARAMS, e))?; + if let Err(e) = check_arguments(&self.tools.list(), name, &args) { + return if self.options.tool_errors_as_results { Ok(text_result(e, true)) } else { Err((INVALID_PARAMS, e)) }; + } Ok(self.tools.call(name, &args)) } "resources/list" => Ok(json!({"resources": self.tools.resources()})), diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs index b687ee2e8..3f8f8d315 100644 --- a/crates/mcp-server/src/tests.rs +++ b/crates/mcp-server/src/tests.rs @@ -1,7 +1,8 @@ use serde_json::{Value, json}; use crate::{ - Contents, Effect, Info, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, tool, + Contents, Effect, Info, Options, PROTOCOL_VERSION, Reference, SUPPORTED_VERSIONS, Server, Tools, check_arguments, object, string, text_result, + tool, }; /// One app's tools: `echo` and `level`, nothing behind them (no engine, no design). `log` records @@ -366,3 +367,131 @@ fn every_call_runs_right_after_its_listing() { reply(&mut s, &json!([call("level", json!({})), call("echo", json!({"text": "b"}))])); assert_eq!(s.tools().log, ["list", "list", "call echo", "list", "list", "call level", "list", "call echo"]); } + +fn with(options: Options) -> Server { + Server::new(info(), Echo::default()).with_options(options) +} + +fn call_msg(id: u64, name: &str, args: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": args}}) +} + +/// `websiteUrl` is sent only when set. +#[test] +fn website_url_is_sent_only_when_set() { + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}); + let off = reply(&mut with(Options::default()), &init).unwrap(); + assert!(off["result"]["serverInfo"].get("websiteUrl").is_none(), "{off}"); + let on = reply(&mut with(Options { website_url: Some("https://example.org/echo".into()), ..Options::default() }), &init).unwrap(); + assert_eq!(on["result"]["serverInfo"]["websiteUrl"], "https://example.org/echo"); + assert_eq!(on["result"]["serverInfo"]["name"], "echo"); +} + +/// With `tool_errors_as_results`, argument failures and unknown tools are `isError` results that +/// carry the message and never run the tool; other errors stay JSON-RPC errors. +#[test] +fn tool_errors_as_results_replaces_invalid_params() { + let mut s = with(Options { tool_errors_as_results: true, ..Options::default() }); + let bad = [ + call_msg(1, "echo", json!({})), + call_msg(2, "echo", json!({"text": 3})), + call_msg(3, "echo", json!({"text": "a", "loud": true})), + call_msg(4, "shout", json!({})), + call_msg(5, "echo", json!([])), + call_msg(6, "echo", json!("text")), + call_msg(7, "echo", json!(7)), + ]; + for msg in &bad { + let r = reply(&mut s, msg).unwrap(); + assert!(r.get("error").is_none(), "{r}"); + assert_eq!(r["result"]["isError"], true, "{r}"); + assert!(r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.is_empty()), "{r}"); + } + let r = reply(&mut s, &bad[0]).unwrap(); + assert_eq!(r["result"]["content"][0]["text"], "echo: missing required argument `text`"); + assert!(s.tools().calls.is_empty()); + let ok = reply(&mut s, &call_msg(8, "echo", json!({"text": "hi"}))).unwrap(); + assert_eq!(ok["result"], json!({"content": [{"type": "text", "text": "hi"}]})); + let nomethod = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 9, "method": "nope"})).unwrap(); + assert_eq!(nomethod["error"]["code"], -32601); + let noname = reply(&mut s, &json!({"jsonrpc": "2.0", "id": 10, "method": "tools/call", "params": {}})).unwrap(); + assert_eq!(noname["error"]["code"], -32602); + // Unchanged with the option off. + let mut off = with(Options::default()); + for msg in &bad { + assert_eq!(reply(&mut off, msg).unwrap()["error"]["code"], -32602); + } +} + +/// With `strict_request_ids`, an id that is not a string or number is -32600 with a null id; the +/// tool never runs. Off, such ids are echoed as before. Notifications have no id and are unaffected. +#[test] +fn strict_request_ids_refuse_other_id_types() { + let odd = [json!(null), json!(true), json!({"a": 1}), json!([1])]; + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in &odd { + let msg = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "x"}}}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!(r["error"]["code"], -32600, "{id}: {r}"); + assert_eq!(r["id"], Value::Null); + let r = reply(&mut off, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["id"], *id); + assert_eq!(r["result"], json!({})); + } + assert!(on.tools().calls.is_empty()); + for id in [json!("a"), json!(1), json!(1.5), json!(-3)] { + let r = reply(&mut on, &json!({"jsonrpc": "2.0", "id": id, "method": "ping"})).unwrap(); + assert_eq!(r["result"], json!({}), "{id}"); + } + assert!(reply(&mut on, ¬ification()).is_none()); +} + +/// The missing-`method` error follows the same id rule: strict mode echoes only string and number +/// ids and answers with a null id for the rest; off, ids are echoed as before. +#[test] +fn strict_request_ids_apply_to_the_missing_method_error() { + let mut on = with(Options { strict_request_ids: true, ..Options::default() }); + let mut off = with(Options::default()); + for id in [json!(true), json!({"a": 1}), json!([1])] { + let msg = json!({"jsonrpc": "2.0", "id": id}); + let r = reply(&mut on, &msg).unwrap(); + assert_eq!((r["error"]["code"].clone(), r["id"].clone()), (json!(-32600), Value::Null), "{id}"); + assert_eq!(reply(&mut off, &msg).unwrap()["id"], id); + } + for id in [json!("a"), json!(7)] { + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0", "id": id})).unwrap()["id"], id); + } + assert_eq!(reply(&mut on, &json!({"jsonrpc": "2.0"})).unwrap()["id"], Value::Null); +} + +/// Hostile input with every option on: oversized and non-UTF-8 lines, odd ids and wrongly typed +/// arguments are answered and serving goes on, and nothing panics. +#[test] +fn every_option_on_survives_hostile_input() { + let mut input = vec![b'x'; (1 << 16) + 10]; + input.push(b'\n'); + input.extend_from_slice(b"\xff\xfe\n"); + for id in ["null", "true", "{}", "[]", "\"s\"", "1e999"] { + input.extend_from_slice( + format!( + "{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"tools/call\",\"params\":{{\"name\":\"echo\",\"arguments\":{{\"text\":{id}}}}}}}\n" + ) + .as_bytes(), + ); + } + for args in ["null", "1", "\"a\"", "[]", "{\"text\":[1]}", "{\"text\":{}}"] { + input.extend_from_slice( + format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"level\",\"arguments\":{args}}}}}\n").as_bytes(), + ); + } + input.extend_from_slice(json!({"jsonrpc": "2.0", "id": 9, "method": "ping"}).to_string().as_bytes()); + let mut output = Vec::new(); + let options = Options { website_url: Some("https://example.org".into()), tool_errors_as_results: true, strict_request_ids: true }; + with(options).serve(std::io::Cursor::new(input), &mut output).unwrap(); + let replies: Vec = String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 2 + 6 + 6 + 1, "{replies:?}"); + assert_eq!(replies[0]["error"]["code"], -32600); + assert_eq!(replies[1]["error"]["code"], -32700); + assert_eq!(replies.last().map(|r| &r["result"]), Some(&json!({}))); +} From b21c69300cb4c00bac2a93306d75e42dbdbaa909 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 08:01:14 +0000 Subject: [PATCH 009/311] Contract stubs: craft-codepage craft-i18n craft-host craft-quit craft-theme craft-keymap craft-behavior craft-settings craft-platform --- Cargo.lock | 1 + crates/behavior/src/cursor.rs | 11 +- crates/behavior/src/fit.rs | 16 +- crates/behavior/src/geometry/mod.rs | 3 +- crates/behavior/src/geometry/quad.rs | 10 + crates/behavior/src/geometry/snap.rs | 32 +- crates/codepage/src/lib.rs | 23 ++ crates/host/src/files.rs | 66 +++- crates/i18n/src/bidi.rs | 16 + crates/i18n/src/lib.rs | 2 +- crates/keymap/src/mnemonic.rs | 7 + crates/platform/src/appearance.rs | 2 + crates/platform/src/appearance/files.rs | 10 + crates/platform/src/browser_files.rs | 102 ++++++ crates/platform/src/clipboard.rs | 4 + crates/platform/src/clipboard/backend.rs | 20 +- crates/platform/src/clipboard/event.rs | 25 ++ crates/platform/src/clipboard/facade.rs | 10 + crates/platform/src/clipboard/memory.rs | 39 +++ crates/platform/src/clipboard/offer/macos.rs | 1 + crates/platform/src/clipboard/offer/mod.rs | 64 ++++ crates/platform/src/clipboard/offer/unix.rs | 22 ++ .../platform/src/clipboard/offer/windows.rs | 8 + crates/platform/src/clipboard/types.rs | 8 + crates/platform/src/lib.rs | 2 + crates/platform/src/logs/crash.rs | 7 + crates/platform/src/open.rs | 13 + crates/quit/src/close.rs | 6 + crates/settings/Cargo.toml | 1 + crates/settings/src/document.rs | 37 +- crates/settings/src/error.rs | 2 +- crates/settings/src/files.rs | 18 + crates/settings/src/files/local_storage.rs | 49 +++ crates/settings/src/lib.rs | 13 +- crates/settings/src/migrate.rs | 8 +- crates/settings/src/paths.rs | 28 +- crates/settings/src/recovery.rs | 5 + crates/settings/src/store.rs | 20 +- crates/settings/src/store/sections.rs | 2 +- crates/ui-contract/src/style/mod.rs | 4 +- vendor/hayro-jbig2/src/arithmetic_decoder.rs | 23 +- vendor/hayro-jbig2/src/bitmap.rs | 63 +--- vendor/hayro-jbig2/src/decode/generic.rs | 270 ++++----------- .../src/decode/generic_refinement.rs | 145 ++------ vendor/hayro-jbig2/src/decode/halftone.rs | 159 ++------- vendor/hayro-jbig2/src/decode/mod.rs | 24 +- vendor/hayro-jbig2/src/decode/pattern.rs | 79 +---- vendor/hayro-jbig2/src/decode/symbol.rs | 263 ++++---------- vendor/hayro-jbig2/src/decode/text.rs | 321 ++++-------------- vendor/hayro-jbig2/src/file.rs | 38 +-- vendor/hayro-jbig2/src/gray_scale.rs | 59 +--- vendor/hayro-jbig2/src/huffman_table.rs | 160 ++------- vendor/hayro-jbig2/src/integer_decoder.rs | 15 +- vendor/hayro-jbig2/src/integration.rs | 11 +- vendor/hayro-jbig2/src/lib.rs | 190 ++--------- vendor/hayro-jbig2/src/page_info.rs | 26 +- vendor/hayro-jbig2/src/pdfcraft_tests.rs | 4 +- vendor/hayro-jbig2/src/segment.rs | 29 +- vendor/hayro-jbig2/src/simd.rs | 69 +--- vendor/hayro-jbig2/src/symbol_id_decoder.rs | 5 +- 60 files changed, 1070 insertions(+), 1600 deletions(-) create mode 100644 crates/platform/src/appearance/files.rs create mode 100644 crates/platform/src/browser_files.rs create mode 100644 crates/platform/src/clipboard/memory.rs create mode 100644 crates/platform/src/clipboard/offer/macos.rs create mode 100644 crates/platform/src/clipboard/offer/mod.rs create mode 100644 crates/platform/src/clipboard/offer/unix.rs create mode 100644 crates/platform/src/clipboard/offer/windows.rs create mode 100644 crates/settings/src/files/local_storage.rs diff --git a/Cargo.lock b/Cargo.lock index dcdeaed12..c435f7dac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3626,6 +3626,7 @@ dependencies = [ "tempfile", "toml", "toml_edit", + "web-time", ] [[package]] diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index f6dd7230c..c27700ea3 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -196,6 +196,8 @@ pub enum PaintedCursor { Arrow { /// The arrow is drawn hollow. hollow: bool, + /// The art turns about its hotspot to point along this direction; `None` is the base art. + toward: Option, }, /// An I-beam across a path with a filled triangle toward each grabbable side. #[non_exhaustive] @@ -216,6 +218,8 @@ pub enum PaintedCursor { }, /// No cursor at all. Hidden, + /// A plain I-beam, visible on light and dark. + IBeam, } impl PaintedCursor { @@ -275,7 +279,12 @@ impl PaintedCursor { /// An arrow with its tip on the hotspot, hollow when `hollow`. pub const fn arrow(hollow: bool) -> Self { - PaintedCursor::Arrow { hollow } + PaintedCursor::Arrow { hollow, toward: None } + } + + /// A solid arrow turned about its hotspot to point along `dir`. + pub const fn arrow_toward(dir: Vec2) -> Self { + PaintedCursor::Arrow { hollow: false, toward: Some(dir) } } /// An I-beam across the path with a triangle toward each grabbable side. diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 8b57e2b93..e44a68293 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -208,12 +208,20 @@ pub struct FitItem { pub section: u16, /// Whether the item may overflow. pub keep: FitKeep, + /// The extent of the item's shorter form, if it has one. + pub short: Option, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep } + FitItem { extent, section, keep, short: None } + } + + /// The item with a shorter form `extent` long, which it takes before any free item leaves. + pub const fn short(mut self, extent: f32) -> Self { + self.short = Some(extent); + self } } @@ -225,6 +233,8 @@ pub struct Fit { pub shown: Vec, /// The items in the overflow menu; empty when everything fits. pub overflow: Vec, + /// The shown items that take their shorter form, as indexes into the input. + pub short: Vec, } fn item_extent(value: f32) -> f64 { @@ -255,7 +265,7 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); let mut shown: Vec = items.iter().map(|item| item.keep != FitKeep::Menu).collect(); if shown.iter().all(|shown| *shown) && run_extent(items, &shown, gap, section_gap) <= available { - return Fit { shown: (0..items.len()).collect(), overflow: Vec::new() }; + return Fit { shown: (0..items.len()).collect(), overflow: Vec::new(), short: Vec::new() }; } let fits = |shown: &[bool]| { let before_control = if shown.iter().any(|shown| *shown) { gap } else { 0.0 }; @@ -266,5 +276,5 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, shown[last] = false; } let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); - Fit { shown: kept, overflow: left } + Fit { shown: kept, overflow: left, short: Vec::new() } } diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index 24886f10d..434fd68df 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -27,5 +27,6 @@ pub use outside::outside_pieces; pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; pub use selection_op::SelectionOperation; pub use snap::{ - SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapTarget, SnapTargets, across_axis, coordinate_across, motion_across, + SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across, + motion_across, }; diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index dcf053241..d0265f358 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -100,6 +100,9 @@ pub enum ScaleRule { /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, + /// A corner keeps the proportions (⇧ frees them) and an edge stretches its one axis; distinct from + /// [`ScaleRule::Shape`] and [`ScaleRule::Proportional`]. + Corners, } /// What the box's content allows. PhotoCraft: editable type refuses distort and perspective @@ -285,6 +288,7 @@ impl BoxRules { } match self.scale { ScaleRule::Shape => shape_mods(part, mods), + ScaleRule::Corners => corners_mods(part, mods), scale => { let legacy = scale == ScaleRule::Free; legacy_mods(legacy, part, unlinked_mods(!self.aspect_linked, legacy, part, mods)) @@ -313,6 +317,12 @@ pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: P apply_mode_drag(&g, to, rules, mods) } +/// The [`ScaleRule::Corners`] rule: a corner keeps the proportions unless ⇧ frees it, an edge stretches its one axis. +fn corners_mods(part: BoxPart, mods: Mods) -> Mods { + let _ = (part, mods); + todo!("cv.K34") +} + /// The shape bounds box's rule: a corner keeps the proportions along the diagonal and an edge /// stretches its one axis, whatever ⇧ and the aspect link say. ⌘ gestures are left alone. fn shape_mods(part: BoxPart, mut mods: Mods) -> Mods { diff --git a/crates/behavior/src/geometry/snap.rs b/crates/behavior/src/geometry/snap.rs index 50889a4f2..2dcbc1543 100644 --- a/crates/behavior/src/geometry/snap.rs +++ b/crates/behavior/src/geometry/snap.rs @@ -158,15 +158,37 @@ pub struct SnapOptions { pub selection: bool, /// View › Show › Smart Guides. pub smart_guides: bool, + /// The key that suspends snapping. + pub suspend: SnapSuspend, } impl Default for SnapOptions { /// Photoshop's defaults: everything on. fn default() -> Self { - Self { on: true, guides: true, grid: true, layers: true, document_bounds: true, selection: true, smart_guides: true } + Self { + on: true, + guides: true, + grid: true, + layers: true, + document_bounds: true, + selection: true, + smart_guides: true, + suspend: SnapSuspend::default(), + } } } +/// The key that suspends snapping. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum SnapSuspend { + /// The Control key. + #[default] + Control, + /// The Alt key. + Alt, +} + /// How the host snaps a tool's pointer. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -291,6 +313,14 @@ impl SnapTargets { /// The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of /// `value` across them; [`SnapTargets::nearest`] is this with [`SnapKinds::ALL`]. pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option { + self.nearest_within(along, value, None, tolerance, kinds) + } + + /// [`nearest_of`](Self::nearest_of) that also takes the query's extent `across` the other axis: a target with a + /// span catches only a point or box overlapping that span there; without `across`, or for a target without a + /// span, it is `nearest_of`. + pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option { + let _ = across; // P3(canvas-w4): cv.K36 let mut best: Option<(f64, SnapTarget)> = None; for target in self.targets.iter().filter(|t| t.along == along && kinds.contains(t.kind)) { let distance = (target.position - value).abs(); diff --git a/crates/codepage/src/lib.rs b/crates/codepage/src/lib.rs index 1b7221fd6..adb5bd06d 100644 --- a/crates/codepage/src/lib.rs +++ b/crates/codepage/src/lib.rs @@ -282,6 +282,29 @@ pub fn is_text_code_page(code_page: u16) -> bool { is_byte_code_page(code_page) || is_multibyte_code_page(code_page) } +/// The character an Alt+numpad `code` types: a decimal code read as an ANSI (`ansi`) or, with a +/// leading zero, OEM (`oem`) code page byte; `None` when it names no insertable character. +#[allow(dead_code)] // P3(shell-w1): sh.K7 +pub fn alt_code_char(code: &str, ansi: u16, oem: u16) -> Option { + let _ = (code, ansi, oem); + todo!("sh.K7") +} + +/// The Windows ANSI and OEM code pages of `locale` (a BCP 47 tag; `None` for the system's), as +/// `(ansi, oem)`. +#[allow(dead_code)] // P3(shell-w1): sh.K7 +pub fn windows_code_pages(locale: Option<&str>) -> (u16, u16) { + let _ = locale; + todo!("sh.K7") +} + +/// Characters Alt+numpad accepts: not control characters, breaks or object placeholders. +#[allow(dead_code)] // P3(shell-w1): sh.K7 +fn codeable(c: char) -> bool { + let _ = c; + todo!("sh.K7") +} + /// The code page of an RTF or Word font charset (`\fcharset`): 204 Russian → 1251, 238 Eastern /// European → 1250, 77 Mac → 10000, 254 PC / 255 OEM → 437, 128 Japanese → 932, 129 Korean → 949, /// 134 Simplified Chinese → 936, 136 Traditional Chinese → 950, 2 Symbol → [`SYMBOL_CODE_PAGE`]… diff --git a/crates/host/src/files.rs b/crates/host/src/files.rs index 4dce84d99..4dd7f51d0 100644 --- a/crates/host/src/files.rs +++ b/crates/host/src/files.rs @@ -65,6 +65,10 @@ pub struct PickRequest { pub file_name: Option, /// The extension a Save answer gets when the user typed none (`"png"`), lowercase. pub suggested_extension: Option, + /// Forces the in-app chooser for this request. + pub fallback: bool, + /// The save makes the document a new file on the host page; other services ignore it. + pub save_as: bool, } impl PickRequest { @@ -79,6 +83,8 @@ impl PickRequest { default_directory: None, file_name: None, suggested_extension: None, + fallback: false, + save_as: false, } } @@ -138,6 +144,19 @@ impl PickRequest { self.suggested_extension = Some(extension.into().trim_start_matches('.').to_ascii_lowercase()); self } + + /// Forces the in-app chooser for this request. + pub fn fallback(mut self, on: bool) -> Self { + let _ = (&mut self, on); + todo!("sh.K12") + } + + /// Makes the save a new file on the host page: a Save As, or a Save under a name the page + /// never sent. + pub fn save_as(mut self, on: bool) -> Self { + let _ = (&mut self, on); + todo!("pf.C-F8") + } } /// The ticket of a pending pick; the answer carries it back. @@ -159,6 +178,8 @@ pub enum Picked { /// the text is the technical cause, not a sentence for the user. A feature without a status /// line to report on treats it as nothing chosen. Unavailable(String), + /// A chosen save path that could not be written; the message is the system's. + Failed(String), } impl Picked { @@ -167,7 +188,7 @@ impl Picked { match self { Picked::Paths(paths) => paths.first().cloned(), Picked::Contents(files) => files.first().map(|(name, _)| PathBuf::from(name)), - Picked::Cancelled | Picked::Unavailable(_) => None, + Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) => None, } } @@ -176,7 +197,7 @@ impl Picked { match self { Picked::Paths(paths) => paths.clone(), Picked::Contents(files) => files.iter().map(|(name, _)| PathBuf::from(name)).collect(), - Picked::Cancelled | Picked::Unavailable(_) => Vec::new(), + Picked::Cancelled | Picked::Unavailable(_) | Picked::Failed(_) => Vec::new(), } } } @@ -249,6 +270,15 @@ pub trait Files: Send + Sync { fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError>; /// The folder the last answered pick of `purpose` chose. fn last_folder(&self, purpose: &str) -> Option; + /// Queues a save of `bytes` as ticket `request`'s answer, taken with + /// [`take_answer`](Files::take_answer): the desktop service asks for the path, then writes + /// atomically; the browser service opens the save picker or makes one download. Counted in + /// [`pick_pending`](Files::pick_pending). + fn save(&self, request: PickRequest, bytes: Vec) -> PickId; + /// Whether a pick can answer paths that [`read`](Files::read) opens again. + fn can_pick(&self) -> bool; + /// Whether [`save`](Files::save) hands the bytes to the browser instead of writing a path. + fn browser_saves(&self) -> bool; } /// No pickers (every pick answers `Cancelled`); reads and writes go to the file system. The @@ -307,6 +337,19 @@ impl Files for NoPickFiles { fn last_folder(&self, _purpose: &str) -> Option { None } + + fn save(&self, request: PickRequest, bytes: Vec) -> PickId { + let _ = (request, bytes); + todo!("pf.C-F1") + } + + fn can_pick(&self) -> bool { + false + } + + fn browser_saves(&self) -> bool { + false + } } /// A file service that answers from a script, for tests of the features that ask for files. It @@ -367,6 +410,12 @@ impl ScriptedFiles { self } + /// A service that stands in for a browser host: [`Files::can_pick`] answers false and + /// [`Files::browser_saves`] true. + pub fn in_browser(self) -> Self { + todo!("pf.C-F7") + } + /// Puts a file in memory, for [`Files::read`]. pub fn with_file(self, path: impl Into, bytes: impl Into>) -> Self { self.state().files.insert(path.into(), bytes.into()); @@ -465,6 +514,19 @@ impl Files for ScriptedFiles { fn last_folder(&self, _purpose: &str) -> Option { None } + + fn save(&self, request: PickRequest, bytes: Vec) -> PickId { + let _ = (request, bytes); + todo!("pf.C-F1") + } + + fn can_pick(&self) -> bool { + todo!("pf.C-F7") + } + + fn browser_saves(&self) -> bool { + todo!("pf.C-F7") + } } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/i18n/src/bidi.rs b/crates/i18n/src/bidi.rs index 6447b3bed..b37ae554f 100644 --- a/crates/i18n/src/bidi.rs +++ b/crates/i18n/src/bidi.rs @@ -2,6 +2,8 @@ use unicode_bidi::{BidiClass, bidi_class}; +use crate::scripts::Direction; + pub(super) const LRI: char = '\u{2066}'; pub(super) const RLI: char = '\u{2067}'; pub(super) const FSI: char = '\u{2068}'; @@ -30,6 +32,20 @@ pub fn ltr(value: &str) -> String { wrap(LRI, value) } +/// A file name for display in an interface of `direction`: unchanged for left-to-right, an +/// isolate with a left-to-right mark before a short extension for right-to-left. +pub fn file_name(name: &str, direction: Direction) -> String { + let _ = (name, direction); + todo!("sh.K18") +} + +/// A path for display in an interface of `direction`: unchanged for left-to-right, a left-to-right +/// isolate with marks after every separator and before a short extension for right-to-left. +pub fn path(value: &str, direction: Direction) -> String { + let _ = (value, direction); + todo!("sh.K18") +} + /// `text` without isolate marks (LRI, RLI, FSI, PDI): a [`crate::fmt`] or [`crate::I18n::trn`] result made fit /// for a file name, a log or a comparison. pub fn strip_isolates(text: &str) -> String { diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index 4729b1138..74b506f4a 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -33,7 +33,7 @@ use bidi::{FSI, has_bidi_control, has_rtl, is_one_isolate, unwrap_isolate, wrap} use negotiation::posix_env_tags; use negotiation::{bare, candidates, is_region, marked, plural_rules}; -pub use bidi::{isolate, ltr, strip_isolates}; +pub use bidi::{file_name, isolate, ltr, path, strip_isolates}; /// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`. mod data { diff --git a/crates/keymap/src/mnemonic.rs b/crates/keymap/src/mnemonic.rs index 29e4cebb4..d4a294043 100644 --- a/crates/keymap/src/mnemonic.rs +++ b/crates/keymap/src/mnemonic.rs @@ -61,6 +61,13 @@ pub fn assign(labels: &[&str], folder: &Folder) -> Vec> { out } +/// The keytip badge of each `(label, requested badge)` in a bar, in three passes; `reserved` letters are never +/// assigned and no badge is a prefix of another. +pub fn assign_keytips(labels: &[(&str, Option<&str>)], reserved: &[char], folder: &Folder) -> Vec { + let _ = (labels, reserved, folder); + todo!("rb.R16") +} + fn first_unused(text: &str, used: &[char], turkic: bool) -> Option<(char, usize)> { let mut previous_alnum = false; let mut starts = Vec::new(); diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs index d92ac9db8..43bbb4d7c 100644 --- a/crates/platform/src/appearance.rs +++ b/crates/platform/src/appearance.rs @@ -343,5 +343,7 @@ fn is_gnome_session(var: &dyn Fn(&str) -> Option) -> bool { var("KDE_FULL_SESSION").is_none() && var("GNOME_DESKTOP_SESSION_ID").is_some() } +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +mod files; #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod portal; diff --git a/crates/platform/src/appearance/files.rs b/crates/platform/src/appearance/files.rs new file mode 100644 index 000000000..2204b3766 --- /dev/null +++ b/crates/platform/src/appearance/files.rs @@ -0,0 +1,10 @@ +//! Motion from the GNOME and KDE settings files, for a desktop whose portal does not answer. + +use std::path::Path; + +/// Whether the desktop's settings files under `config_home` ask for reduced motion; `None` when they say nothing. +#[allow(dead_code)] // P3(platform-w6): pf.C-O4 +pub(crate) fn reduced_motion_from_files(config_home: &Path) -> Option { + let _ = config_home; + todo!("pf.C-O4") +} diff --git a/crates/platform/src/browser_files.rs b/crates/platform/src/browser_files.rs new file mode 100644 index 000000000..f5a5eb845 --- /dev/null +++ b/crates/platform/src/browser_files.rs @@ -0,0 +1,102 @@ +//! The browser's file service: picks and saves through the page. + +use std::path::{Path, PathBuf}; + +use craft_host::{FileError, Files, PickId, PickRequest, Picked}; + +/// How much a browser pick may hand over. +#[derive(Clone, Copy, Debug)] +pub struct PickLimits { + /// The most files one pick answers. + pub files: usize, + /// The most bytes of picked files held before they are taken. + pub pending_bytes: usize, +} + +impl PickLimits { + /// The limits of production's web build: 2000 files and 256 MiB. + pub const DEFAULT: PickLimits = PickLimits { files: 2000, pending_bytes: 256 << 20 }; +} + +/// Browser picks and saves. [`Files::can_pick`] answers false and [`Files::browser_saves`] true. The save picker +/// is reached through `js_sys::Reflect`, and a save it refuses falls back to one download. +pub struct BrowserFiles { + _limits: PickLimits, +} + +impl BrowserFiles { + /// A service whose late answers call `wake`. + pub fn new(wake: impl Fn() + Send + Sync + 'static) -> Self { + let _ = wake; + todo!("pf.C-F6") + } + + /// The service with `limits` in place of [`PickLimits::DEFAULT`]. + pub fn limits(self, limits: PickLimits) -> Self { + let _ = (&self, limits); + todo!("pf.C-F6") + } +} + +/// The MIME type a picked file of `name` is read as. +#[allow(dead_code)] // P3(platform-w5): pf.C-F6 +fn mime_for(name: &str) -> &'static str { + let _ = name; + todo!("pf.C-F6") +} + +/// What a rejected save picker answers: a cancel for `AbortError` (`error_name`), otherwise the `download` fallback's outcome. +#[allow(dead_code)] // P3(platform-w5): pf.C-F6 +pub(crate) fn rejected(error_name: &str, download: impl FnOnce() -> Result<(), String>) -> Picked { + let _ = (error_name, download); + todo!("pf.C-F6") +} + +impl Files for BrowserFiles { + fn pick(&self, request: PickRequest) -> PickId { + let _ = request; + todo!("pf.C-F6") + } + + fn take_answer(&self, id: PickId) -> Option { + let _ = id; + todo!("pf.C-F6") + } + + fn forget(&self, id: PickId) { + let _ = id; + todo!("pf.C-F6") + } + + fn pick_pending(&self) -> bool { + todo!("pf.C-F6") + } + + fn read(&self, path: &Path) -> Result, FileError> { + let _ = path; + todo!("pf.C-F6") + } + + fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> { + let _ = (path, bytes); + todo!("pf.C-F6") + } + + fn last_folder(&self, purpose: &str) -> Option { + let _ = purpose; + todo!("pf.C-F6") + } + + fn save(&self, request: PickRequest, bytes: Vec) -> PickId { + let _ = (request, bytes); + todo!("pf.C-F6") + } + + fn can_pick(&self) -> bool { + false + } + + fn browser_saves(&self) -> bool { + true + } +} diff --git a/crates/platform/src/clipboard.rs b/crates/platform/src/clipboard.rs index bf5cce9e0..d102761c9 100644 --- a/crates/platform/src/clipboard.rs +++ b/crates/platform/src/clipboard.rs @@ -17,12 +17,16 @@ mod backend; mod convert; mod event; mod facade; +mod memory; +#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] +mod offer; mod probe; mod types; pub use backend::*; pub use event::*; pub use facade::*; +pub use memory::MemoryClipboard; pub use probe::*; pub use types::*; diff --git a/crates/platform/src/clipboard/backend.rs b/crates/platform/src/clipboard/backend.rs index 1a6a78160..6ca4cc82d 100644 --- a/crates/platform/src/clipboard/backend.rs +++ b/crates/platform/src/clipboard/backend.rs @@ -5,6 +5,8 @@ use std::borrow::Cow; use std::path::PathBuf; use super::convert::{rgba8_flavor, rgba8_image, trim_cr, uri_list}; +#[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] +use super::offer; use super::types::{BITMAP, ClipboardError, ClipboardImage, Flavor, HTML, PNG, RGBA8, TEXT, URI_LIST}; /// What a write did. @@ -40,6 +42,18 @@ pub trait ClipboardBackend: Send { /// The flavours of a paste the host delivered as an event (the browser's Paste). Only /// [`EventClipboard`] keeps them; the system clipboard ignores them. fn offer(&mut self, _flavors: Vec) {} + /// The MIME names of the formats on offer. + fn formats(&mut self) -> Vec { + Vec::new() + } + /// Whether this process owns the clipboard; `None` when the backend cannot tell. + fn owns(&mut self) -> Option { + None + } + /// Whether a late paste arrived since the last call. + fn take_arrived(&mut self) -> bool { + false + } } /// The desktop's clipboard through arboard: X11 and Wayland, macOS, Windows. Not on wasm. @@ -58,6 +72,10 @@ pub struct SystemClipboard { unreadable: bool, decode: Option, presence: presence::Presence, + #[allow(dead_code)] // P3(platform-w1): pf.C-P6 + offer: offer::Offer, + #[allow(dead_code)] // P3(platform-w1): pf.C-P6 + owner: [u8; 16], } /// The app's decoder for encoded bitmaps ([`SystemClipboard::decoder`]). @@ -68,7 +86,7 @@ pub(crate) type Decode = Box Option + Send>; impl SystemClipboard { /// A clipboard that connects to the system clipboard on first use. pub fn new() -> Self { - Self { handle: None, unreadable: false, decode: None, presence: presence::Presence::new() } + Self { handle: None, unreadable: false, decode: None, presence: presence::Presence::new(), offer: offer::Offer::new(), owner: [0; 16] } } /// Decodes a [`PNG`] flavor to pixels for [`ClipboardBackend::write`], which hands the diff --git a/crates/platform/src/clipboard/event.rs b/crates/platform/src/clipboard/event.rs index bcd642711..ab2b8e9d3 100644 --- a/crates/platform/src/clipboard/event.rs +++ b/crates/platform/src/clipboard/event.rs @@ -21,6 +21,20 @@ pub struct EventClipboard { out: CopyOut, } +/// The queue of an [`EventClipboard`] for a paste the browser delivers outside a pass; `Send + Sync`. +#[derive(Clone)] +pub struct LateOffers { + _queued: (), +} + +impl LateOffers { + /// Queues a paste's flavours and wakes the app. + pub fn offer(&self, flavors: Vec) { + let _ = flavors; + todo!("pf.C-P9") + } +} + /// The number of the host's current pass; it changes when a pass ends. pub(super) type PassClock = Box u64 + Send>; @@ -35,6 +49,17 @@ impl EventClipboard { Self { pasted: Vec::new(), offered_in: 0, pass: Box::new(pass), out: Box::new(out) } } + /// The handle a thread outside the pass queues a late paste through. + pub fn late_offers(&self) -> LateOffers { + todo!("pf.C-P9") + } + + /// Runs `wake` when a late paste is queued, so the app takes it on its next pass. + pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> Self { + let _ = (&self, wake); + todo!("pf.C-P9") + } + /// The first of `mimes` this pass's paste offered; [`BITMAP`] is any offered `image/*`. fn offered(&self, mimes: &[&str]) -> Option<&Flavor> { if (self.pass)() != self.offered_in { diff --git a/crates/platform/src/clipboard/facade.rs b/crates/platform/src/clipboard/facade.rs index fa8bc9ce3..90e687175 100644 --- a/crates/platform/src/clipboard/facade.rs +++ b/crates/platform/src/clipboard/facade.rs @@ -127,6 +127,16 @@ impl Clipboard { self.backend.has(mimes) } + /// The MIME names of the formats on offer. + pub fn formats(&mut self) -> Vec { + todo!("pf.C-P8") + } + + /// Whether a late paste arrived since the last call. + pub fn take_arrived_paste(&mut self) -> bool { + todo!("pf.C-P8") + } + /// Does the clipboard still hold what this app wrote last (nothing copied since, here or in /// another app)? Reads the clipboard's flavour of the type the backend wrote last and compares /// it with what was written (an image by [`image_signature`]); for a pasted image the app diff --git a/crates/platform/src/clipboard/memory.rs b/crates/platform/src/clipboard/memory.rs new file mode 100644 index 000000000..c7548e159 --- /dev/null +++ b/crates/platform/src/clipboard/memory.rs @@ -0,0 +1,39 @@ +//! An in-memory clipboard. + +use std::path::PathBuf; + +use super::backend::ClipboardBackend; +use super::types::{ClipboardError, ClipboardImage, Flavor}; + +/// The public in-memory clipboard for tests and hosts without one. +#[derive(Default)] +pub struct MemoryClipboard { + held: Vec, +} + +impl ClipboardBackend for MemoryClipboard { + fn write(&mut self, flavors: &[Flavor]) -> Result { + let _ = (&self.held, flavors); + todo!("pf.C-P10") + } + + fn read(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + let _ = (mimes, limit); + todo!("pf.C-P10") + } + + fn read_image(&mut self, limit: u64) -> Result, ClipboardError> { + let _ = limit; + todo!("pf.C-P10") + } + + fn read_files(&mut self, limit: usize) -> Result>, ClipboardError> { + let _ = limit; + todo!("pf.C-P10") + } + + fn has(&mut self, mimes: &[&str]) -> bool { + let _ = mimes; + todo!("pf.C-P10") + } +} diff --git a/crates/platform/src/clipboard/offer/macos.rs b/crates/platform/src/clipboard/offer/macos.rs new file mode 100644 index 000000000..8b2add51d --- /dev/null +++ b/crates/platform/src/clipboard/offer/macos.rs @@ -0,0 +1 @@ +//! The offer on macOS. diff --git a/crates/platform/src/clipboard/offer/mod.rs b/crates/platform/src/clipboard/offer/mod.rs new file mode 100644 index 000000000..96b167fd0 --- /dev/null +++ b/crates/platform/src/clipboard/offer/mod.rs @@ -0,0 +1,64 @@ +//! What the system clipboard offers and how it is written, per platform. + +#[cfg(target_os = "macos")] +mod macos; +#[cfg(all(unix, not(target_os = "macos")))] +mod unix; +#[cfg(windows)] +mod windows; + +use super::backend::Decode; +use super::types::{ClipboardError, Flavor}; + +/// The platform's offer state: the cached X11 `TARGETS` connection and the macOS change count recorded at a write. +pub(super) struct Offer { + _state: (), +} + +impl Offer { + /// An offer with nothing cached. + pub(super) fn new() -> Self { + Self { _state: () } + } +} + +/// Every flavour the platform can hold in one offer, tagged with `owner`; the index of the first one written. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn write( + handle: &mut arboard::Clipboard, + offer: &mut Offer, + flavors: &[Flavor], + decode: Option<&Decode>, + owner: &[u8], +) -> Result { + let _ = (handle, offer, flavors, decode, owner); + todo!("pf.C-P7") +} + +/// The clipboard's RTF text, at most `limit` bytes of it. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn read_rtf(offer: &mut Offer, limit: u64) -> Result, ClipboardError> { + let _ = (offer, limit); + todo!("pf.C-P7") +} + +/// The MIME names of the formats on offer. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn formats(offer: &mut Offer) -> Vec { + let _ = offer; + todo!("pf.C-P7") +} + +/// Whether the offer holds one of `mimes`. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn has(offer: &mut Offer, mimes: &[&str]) -> bool { + let _ = (offer, mimes); + todo!("pf.C-P7") +} + +/// Whether this process owns the clipboard, by the `owner` marker; `None` when the platform cannot tell. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn owns(offer: &mut Offer, owner: &[u8]) -> Option { + let _ = (offer, owner); + todo!("pf.C-P7") +} diff --git a/crates/platform/src/clipboard/offer/unix.rs b/crates/platform/src/clipboard/offer/unix.rs new file mode 100644 index 000000000..9d3349157 --- /dev/null +++ b/crates/platform/src/clipboard/offer/unix.rs @@ -0,0 +1,22 @@ +//! The offer on Linux and the BSDs. + +/// Whether the target or MIME names in `offered` contain a format that can be read as `mime`. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn offered_has(offered: &[String], mime: &str) -> bool { + let _ = (offered, mime); + todo!("pf.C-P7") +} + +/// The target that carries RTF among `offered`. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn rtf_target(offered: &[String]) -> Option<&'static str> { + let _ = offered; + todo!("pf.C-P7") +} + +/// Whether a read of `len` bytes with `remaining` left under `cap` is complete. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn complete(len: usize, remaining: usize, cap: usize) -> bool { + let _ = (len, remaining, cap); + todo!("pf.C-P7") +} diff --git a/crates/platform/src/clipboard/offer/windows.rs b/crates/platform/src/clipboard/offer/windows.rs new file mode 100644 index 000000000..fe4ab7529 --- /dev/null +++ b/crates/platform/src/clipboard/offer/windows.rs @@ -0,0 +1,8 @@ +//! The offer on Windows. + +/// `fragment` wrapped as a CF_HTML clipboard payload. +#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +pub(super) fn wrap_cf_html(fragment: &str) -> Vec { + let _ = fragment; + todo!("pf.C-P7") +} diff --git a/crates/platform/src/clipboard/types.rs b/crates/platform/src/clipboard/types.rs index 6107c1608..26f1959f2 100644 --- a/crates/platform/src/clipboard/types.rs +++ b/crates/platform/src/clipboard/types.rs @@ -9,6 +9,8 @@ pub const TEXT: &str = "text/plain"; pub const HTML: &str = "text/html"; /// `text/rtf`. pub const RTF: &str = "text/rtf"; +/// `application/mathml+xml`: one equation as MathML. +pub const MATHML: &str = "application/mathml+xml"; /// `image/png`. pub const PNG: &str = "image/png"; /// `image/svg+xml`. @@ -41,6 +43,12 @@ impl Flavor { Self { mime: mime.into(), data } } + /// `image` as an [`RGBA8`] flavor. + pub fn rgba8(image: &ClipboardImage) -> Flavor { + let _ = image; + todo!("pf.C-P3") + } + /// `text/plain` with `text`. pub fn text(text: &str) -> Self { Self::new(TEXT, text.as_bytes().to_vec()) diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs index 13f43a444..d67527d30 100644 --- a/crates/platform/src/lib.rs +++ b/crates/platform/src/lib.rs @@ -8,6 +8,8 @@ pub mod autosave; mod autosave_tests; #[cfg(all(feature = "browser", target_arch = "wasm32"))] pub mod browser; +#[cfg(all(feature = "browser", target_arch = "wasm32"))] +pub mod browser_files; #[cfg(feature = "clipboard")] pub mod clipboard; #[cfg(all(test, feature = "clipboard"))] diff --git a/crates/platform/src/logs/crash.rs b/crates/platform/src/logs/crash.rs index 4cd124eb6..5e0f8e7ae 100644 --- a/crates/platform/src/logs/crash.rs +++ b/crates/platform/src/logs/crash.rs @@ -105,6 +105,13 @@ pub fn install(app: &'static str, version: &'static str, dir: Option) { }); } +/// `message` with each backticked span replaced by `…`, so a panic text carries no quoted user data. +#[allow(dead_code)] // P3(platform-w6): pf.C-O5 +fn redact_quoted(message: &str) -> String { + let _ = message; + todo!("pf.C-O5") +} + /// Write a fatal error that isn't a panic (the window could not be created) to the crash log. pub fn record(message: &str) { // filmcraft: crates/ui-egui/src/crash.rs:45 diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 6cebea469..7d87a8738 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -82,6 +82,8 @@ pub enum Intake { /// Where they landed. target: DropTarget, }, + /// The OS asked the app to quit. + Quit, } /// The sending side of a [`FileIntake`]: `Send + Clone`, for the threads that hear the OS (the @@ -109,6 +111,17 @@ impl IntakeSender { push(&self.queue, Intake::Open(paths)); self.wake.wake(); } + + /// Queues files dropped on the window and wakes the UI; an empty list is ignored. + pub fn dropped(&self, files: Vec, target: DropTarget) { + let _ = (files, target); + todo!("pf.C-O1") + } + + /// Queues an OS quit request and wakes the UI. + pub fn quit(&self) { + todo!("pf.C-O1") + } } /// Files waiting to be opened, read once per frame on the UI thread (spec Q-S4F-7). diff --git a/crates/quit/src/close.rs b/crates/quit/src/close.rs index ee61eff53..c54baa37e 100644 --- a/crates/quit/src/close.rs +++ b/crates/quit/src/close.rs @@ -176,6 +176,12 @@ impl CloseGuard { self.cancel() } + /// The save failed for real: the saving document returns to the front of the pending ones, + /// the apply-to-all answer clears, and the guard asks about that document again. + pub fn retry_after_failure(&mut self) -> GuardStep { + todo!("sh.K11") + } + /// A document closed elsewhere while the guard ran (a script): it is no longer asked about. pub fn forget(&mut self, doc: &D) { self.pending.retain(|d| d != doc); diff --git a/crates/settings/Cargo.toml b/crates/settings/Cargo.toml index 5bbc50da5..685a6e477 100644 --- a/crates/settings/Cargo.toml +++ b/crates/settings/Cargo.toml @@ -22,6 +22,7 @@ serde = { version = "1", features = ["derive"] } serde_json = { workspace = true } toml = { version = "1.1", default-features = false, features = ["std", "parse", "serde"] } toml_edit = { version = "0.25", features = ["serde"] } +web-time = "1.1" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] dirs = "7" diff --git a/crates/settings/src/document.rs b/crates/settings/src/document.rs index ada9ce836..88502a47b 100644 --- a/crates/settings/src/document.rs +++ b/crates/settings/src/document.rs @@ -5,6 +5,29 @@ use toml_edit::{DocumentMut, Item, Table, TableLike, Value}; use crate::Settings; use crate::error::SectionError; +/// How [`merge_changes`] merges one item path when another process wrote the file meanwhile. The app names the +/// rule per path in [`Settings::merge_rule`]. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub enum MergeRule { + /// Key by key: today's merge. + ByKey, + /// The item as a whole: ours replaces theirs. + Whole, + /// A most-recently-used list of at most `cap` entries; `key` names an entry for de-duplication. + Recent { + /// The most entries kept. + cap: usize, + /// The identity of an entry; `None` for an entry without one. + key: fn(&toml_edit::Value) -> Option, + }, + /// A list of entries merged by identity: `key` names an entry. + Entries { + /// The identity of an entry; `None` for an entry without one. + key: fn(&toml_edit::Value) -> Option, + }, +} + /// The key written first in every `config.toml`. pub const SCHEMA_VERSION_KEY: &str = "schema_version"; @@ -261,7 +284,7 @@ pub fn merge_changes(base: &DocumentMut, ours: &DocumentMut, theirs return; } let base = as_read::(&migrated_base::(base, theirs)); - merge_changed_tables(base.as_table(), ours.as_table(), theirs.as_table_mut()); + merge_changed_tables::(base.as_table(), ours.as_table(), theirs.as_table_mut(), &mut Vec::new()); } /// `doc` with each key `T` reads and `doc` lacks filled in as `T` reads it. @@ -288,15 +311,16 @@ fn migrated_base(base: &DocumentMut, theirs: &DocumentMut) -> Docum migrated } -fn merge_changed_tables(base: &dyn TableLike, ours: &dyn TableLike, theirs: &mut dyn TableLike) { +// P3(platform-w8): pf.C-S1 (`path` is carried but no rule is asked yet) +fn merge_changed_tables(base: &dyn TableLike, ours: &dyn TableLike, theirs: &mut dyn TableLike, path: &mut Vec) { for (key, our_item) in ours.iter() { match (base.get(key), theirs.get_mut(key)) { - (Some(base_item), Some(their_item)) => merge_changed_items(base_item, our_item, their_item), + (Some(base_item), Some(their_item)) => merge_changed_items::(base_item, our_item, their_item, path), // Removed on disk and unchanged here: it stays removed. (Some(base_item), None) if same_item(base_item, our_item) => {} // A key neither `base` nor `T`'s defaults have (a map entry both instances added): every leaf of ours is ours. (None, Some(their_item)) => match (their_item.as_table_like_mut(), our_item.as_table_like()) { - (Some(their_table), Some(our_table)) => merge_changed_tables(&Table::new(), our_table, their_table), + (Some(their_table), Some(our_table)) => merge_changed_tables::(&Table::new(), our_table, their_table, path), _ => replace_item(their_item, our_item), }, (_, None) => { @@ -310,12 +334,13 @@ fn merge_changed_tables(base: &dyn TableLike, ours: &dyn TableLike, theirs: &mut } } -fn merge_changed_items(base: &Item, ours: &Item, theirs: &mut Item) { +// P3(platform-w8): pf.C-S1 +fn merge_changed_items(base: &Item, ours: &Item, theirs: &mut Item, path: &mut Vec) { if same_item(base, ours) { return; } match (base.as_table_like(), ours.as_table_like(), theirs.as_table_like_mut()) { - (Some(base), Some(ours), Some(theirs)) => merge_changed_tables(base, ours, theirs), + (Some(base), Some(ours), Some(theirs)) => merge_changed_tables::(base, ours, theirs, path), _ => replace_item(theirs, ours), } } diff --git a/crates/settings/src/error.rs b/crates/settings/src/error.rs index 86e0ff2a6..996d580f6 100644 --- a/crates/settings/src/error.rs +++ b/crates/settings/src/error.rs @@ -3,7 +3,7 @@ use std::fmt; use std::io; use std::path::PathBuf; -use std::time::Instant; +use web_time::Instant; /// Why a schema migration step failed. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/settings/src/files.rs b/crates/settings/src/files.rs index dde6e2058..b875c938e 100644 --- a/crates/settings/src/files.rs +++ b/crates/settings/src/files.rs @@ -1,6 +1,13 @@ //! [`SettingsFiles`]: the file access a [`SettingsStore`](crate::SettingsStore) goes through, so an //! app can route its settings elsewhere (PhotoCraft's `Services` file closures, browser storage). +#[cfg(target_arch = "wasm32")] +mod local_storage; + +#[cfg(target_arch = "wasm32")] +pub use local_storage::LocalStorageFiles; + +use std::any::Any; use std::io; use std::path::{Path, PathBuf}; @@ -28,6 +35,12 @@ pub trait SettingsFiles: Send + Sync { } /// Whether `dir` accepts a new file. fn check_writable(&self, dir: &Path) -> io::Result<()>; + /// Takes a `.lock` file beside the settings file at `path`, held from the disk check to the write; dropping the + /// box releases it. Files with nothing to lock keep the default, which holds none. + fn lock(&self, path: &Path) -> Option> { + let _ = path; + None + } } /// The file system, through `craft-atomic` and [`recovery`](crate::recovery): what the store does @@ -69,6 +82,11 @@ impl SettingsFiles for DiskFiles { fn check_writable(&self, dir: &Path) -> io::Result<()> { crate::recovery::check_writable(dir) } + + fn lock(&self, path: &Path) -> Option> { + let _ = path; + todo!("pf.C-S3") + } } /// New files are owner-only; on a replace `craft-atomic` keeps the existing file's mode. diff --git a/crates/settings/src/files/local_storage.rs b/crates/settings/src/files/local_storage.rs new file mode 100644 index 000000000..ddce66bfc --- /dev/null +++ b/crates/settings/src/files/local_storage.rs @@ -0,0 +1,49 @@ +//! Browser settings storage: [`LocalStorageFiles`]. + +use std::io; +use std::path::{Path, PathBuf}; + +use super::SettingsFiles; + +/// Browser settings storage under a byte cap. A stored value over the cap reads as absent, so the store uses +/// defaults, and is not reported as damaged. The backup is keyed by +/// [`backup_path`](crate::recovery::backup_path). +#[derive(Clone, Copy, Debug)] +pub struct LocalStorageFiles { + cap: usize, +} + +impl LocalStorageFiles { + /// Storage that ignores a stored value over `cap` bytes. + pub fn new(cap: usize) -> Self { + let _ = cap; + todo!("pf.C-S4") + } +} + +impl SettingsFiles for LocalStorageFiles { + fn read(&self, path: &Path) -> io::Result> { + let _ = (self.cap, path); + todo!("pf.C-S4") + } + + fn write(&self, path: &Path, text: &str) -> io::Result<()> { + let _ = (path, text); + todo!("pf.C-S4") + } + + fn move_aside(&self, path: &Path) -> io::Result { + let _ = path; + todo!("pf.C-S4") + } + + fn write_backup(&self, path: &Path, text: &str) -> io::Result<()> { + let _ = (path, text); + todo!("pf.C-S4") + } + + fn check_writable(&self, dir: &Path) -> io::Result<()> { + let _ = dir; + todo!("pf.C-S4") + } +} diff --git a/crates/settings/src/lib.rs b/crates/settings/src/lib.rs index e3f3ac261..2afe9bde3 100644 --- a/crates/settings/src/lib.rs +++ b/crates/settings/src/lib.rs @@ -44,28 +44,24 @@ mod names; pub mod presets; pub mod remember; -#[cfg(not(target_arch = "wasm32"))] pub mod paths; #[cfg(not(target_arch = "wasm32"))] pub mod profiles; -#[cfg(not(target_arch = "wasm32"))] pub mod recovery; -#[cfg(not(target_arch = "wasm32"))] pub mod store; #[cfg(all(feature = "testing", not(target_arch = "wasm32")))] pub mod testing; +pub use document::MergeRule; pub use error::{LoadReport, MigrateError, ReadOnlyReason, SaveStatus, SectionError, SettingsError, Source, TickResult}; #[cfg(not(target_arch = "wasm32"))] pub use files::DiskFiles; pub use files::SettingsFiles; pub use migrate::LegacyFile; -#[cfg(not(target_arch = "wasm32"))] pub use paths::{Location, Portable, Probe, Resolved, Rule}; #[cfg(not(target_arch = "wasm32"))] pub use profiles::{ProfileError, Profiles}; pub use remember::{Remembered, RememberedSection}; -#[cfg(not(target_arch = "wasm32"))] pub use store::{OpenOptions, SettingsStore, SharedSettings}; pub use toml_edit::DocumentMut; @@ -107,6 +103,13 @@ pub trait Settings: Serialize + DeserializeOwned + Default + Clone + PartialEq { let _ = (from, doc); Ok(()) } + + /// The rule for merging the item at `path` when another process wrote the file meanwhile. The default + /// merges key by key. + fn merge_rule(path: &[&str]) -> MergeRule { + let _ = path; + MergeRule::ByKey + } } #[cfg(test)] diff --git a/crates/settings/src/migrate.rs b/crates/settings/src/migrate.rs index 1c00e1370..8599dc3e5 100644 --- a/crates/settings/src/migrate.rs +++ b/crates/settings/src/migrate.rs @@ -4,9 +4,9 @@ use std::path::PathBuf; use toml_edit::DocumentMut; -use crate::Settings; use crate::document::{schema_version, set_schema_version}; use crate::error::{MigrateError, SectionError}; +use crate::{Settings, SettingsFiles}; /// What [`upgrade`] found. #[derive(Debug, Clone, PartialEq, Eq)] @@ -77,9 +77,9 @@ impl std::fmt::Debug for LegacyFile { /// Tries each legacy file in order and returns the first one that parses, with the values it /// reset and its path. -#[cfg(not(target_arch = "wasm32"))] -pub fn import_legacy(files: &[LegacyFile]) -> Option> { - files.iter().find_map(|f| { +pub fn import_legacy(files: &dyn SettingsFiles, legacy: &[LegacyFile]) -> Option> { + let _ = files; // P3(platform-w8): pf.C-S5 + legacy.iter().find_map(|f| { let bytes = std::fs::read(&f.path).ok()?; (f.parse)(&bytes).ok().map(|(v, errors)| (v, errors, f.path.clone())) }) diff --git a/crates/settings/src/paths.rs b/crates/settings/src/paths.rs index 18d771288..7a4184583 100644 --- a/crates/settings/src/paths.rs +++ b/crates/settings/src/paths.rs @@ -105,7 +105,10 @@ impl Default for Probe { Self { env: Box::new(|name| std::env::var_os(name)), exe_dir: std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)), + #[cfg(not(target_arch = "wasm32"))] platform_config_dir: dirs::config_dir(), + #[cfg(target_arch = "wasm32")] + platform_config_dir: None, } } } @@ -158,6 +161,10 @@ fn resolve_checked( Location::Memory => return Resolved::new(None, Rule::Memory), Location::Auto => {} } + // A browser has no folders: the store keeps its files in `LocalStorageFiles`. + if cfg!(target_arch = "wasm32") { + return Resolved::new(None, Rule::Memory); + } let var = env_var_name(app_id); if let Some(value) = (probe.env)(&var) { if value.is_empty() { @@ -193,7 +200,10 @@ fn resolve_checked( /// Creates `dir` and proves a file can be written in it: a folder can exist and still be read-only. fn ensure_writable(dir: &Path) -> std::io::Result<()> { std::fs::create_dir_all(dir)?; - crate::recovery::check_writable(dir) + #[cfg(not(target_arch = "wasm32"))] + return crate::recovery::check_writable(dir); + #[cfg(target_arch = "wasm32")] + Ok(()) } /// Whether `dir`, or for a folder that doesn't exist yet its nearest existing ancestor (where @@ -236,10 +246,22 @@ fn bundle_parent(exe_dir: &Path) -> Option<&Path> { /// The platform cache folder for `app_id` (`%LOCALAPPDATA%` on Windows, so it does not roam). pub fn cache_dir(app_id: &str) -> Option { - dirs::cache_dir().map(|d| d.join(app_id)) + #[cfg(not(target_arch = "wasm32"))] + return dirs::cache_dir().map(|d| d.join(app_id)); + #[cfg(target_arch = "wasm32")] + { + let _ = app_id; + None + } } /// The platform data folder for `app_id`, for recovery files and other non-settings state. pub fn data_dir(app_id: &str) -> Option { - dirs::data_local_dir().map(|d| d.join(app_id)) + #[cfg(not(target_arch = "wasm32"))] + return dirs::data_local_dir().map(|d| d.join(app_id)); + #[cfg(target_arch = "wasm32")] + { + let _ = app_id; + None + } } diff --git a/crates/settings/src/recovery.rs b/crates/settings/src/recovery.rs index 1435797e0..8eefb25d2 100644 --- a/crates/settings/src/recovery.rs +++ b/crates/settings/src/recovery.rs @@ -1,11 +1,14 @@ //! Keeping damaged and previous files around. +#[cfg(not(target_arch = "wasm32"))] use std::io; use std::path::{Path, PathBuf}; +#[cfg(not(target_arch = "wasm32"))] use std::time::{SystemTime, UNIX_EPOCH}; /// Renames a damaged `config.toml` to `config.broken-.toml` beside it and returns the /// new path. Never overwrites: a name that exists gets a `-` suffix. +#[cfg(not(target_arch = "wasm32"))] pub fn move_aside(path: &Path) -> io::Result { let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("config"); let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml"); @@ -40,6 +43,7 @@ pub fn backup_path(path: &Path) -> PathBuf { /// previous backup. On Unix the backup always gets the same mode and group as `path` (`0600` /// when there is none), so it is never readable by more people than the settings themselves; /// when it cannot be put in the config's group, it keeps the owner bits only. +#[cfg(not(target_arch = "wasm32"))] pub fn write_backup(path: &Path, text: &str) -> io::Result<()> { let backup = backup_path(path); #[cfg(unix)] @@ -69,6 +73,7 @@ pub fn write_backup(path: &Path, text: &str) -> io::Result<()> { } /// Checks that `dir` accepts a new file by creating and removing a probe. +#[cfg(not(target_arch = "wasm32"))] pub fn check_writable(dir: &Path) -> io::Result<()> { let probe = dir.join(format!(".craft-settings-probe-{}", std::process::id())); std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; diff --git a/crates/settings/src/store.rs b/crates/settings/src/store.rs index 23efca9a2..121c91824 100644 --- a/crates/settings/src/store.rs +++ b/crates/settings/src/store.rs @@ -2,14 +2,20 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Duration; + +use web_time::Instant; use toml_edit::DocumentMut; use crate::Settings; use crate::document::{self, merge_changes, merge_into, set_schema_version}; use crate::error::{LoadReport, ReadOnlyReason, SaveStatus, SettingsError, Source, TickResult}; -use crate::files::{DiskFiles, SettingsFiles}; +#[cfg(not(target_arch = "wasm32"))] +use crate::files::DiskFiles; +#[cfg(target_arch = "wasm32")] +use crate::files::LocalStorageFiles; +use crate::files::SettingsFiles; use crate::migrate::{self, LegacyFile, Upgrade}; use crate::paths::{self, Location, Portable, Probe}; @@ -55,7 +61,12 @@ pub struct OpenOptions { impl Default for OpenOptions { fn default() -> Self { - Self { location: Location::Auto, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, probe: Probe::default(), files: Arc::new(DiskFiles) } + #[cfg(not(target_arch = "wasm32"))] + let files: Arc = Arc::new(DiskFiles); + // localStorage holds about 5 MB per site. + #[cfg(target_arch = "wasm32")] + let files: Arc = Arc::new(LocalStorageFiles::new(4 << 20)); + Self { location: Location::Auto, legacy: Vec::new(), debounce: DEFAULT_DEBOUNCE, probe: Probe::default(), files } } } @@ -369,7 +380,8 @@ impl SettingsStore { match self.files.read(path) { Ok(Some(text)) => self.load_text(path, &text, damaged, report), Ok(None) => { - if let Some((value, errors, from)) = migrate::import_legacy(legacy) { + if let Some((value, errors, from)) = migrate::import_legacy(&*self.files, legacy) { + // P3(platform-w8): pf.C-S5 self.value = value; self.dirty = true; report.source = Source::Legacy(from); diff --git a/crates/settings/src/store/sections.rs b/crates/settings/src/store/sections.rs index 491bf89a7..412ca53ad 100644 --- a/crates/settings/src/store/sections.rs +++ b/crates/settings/src/store/sections.rs @@ -1,7 +1,7 @@ //! Library sections: tables beside `T`'s keys in the same document. use std::sync::{Arc, Mutex, MutexGuard}; -use std::time::Instant; +use web_time::Instant; use toml_edit::{DocumentMut, Item}; diff --git a/crates/ui-contract/src/style/mod.rs b/crates/ui-contract/src/style/mod.rs index cfde3b625..d13c35b33 100644 --- a/crates/ui-contract/src/style/mod.rs +++ b/crates/ui-contract/src/style/mod.rs @@ -25,7 +25,9 @@ pub use cx::{GlyphRole, StyleCx, VariantParts}; pub use key::{EnvKey, Ink, StyleKey}; pub(crate) use look::StyleView; pub use look::{ComponentStyle, Corners, DataColor, FocusLook, IconLook, StyleColor, SurfaceKind, SurfaceLook, TextLook, TrackLook}; -pub use paint::{HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarKind, ScrollBarLook, resize_line_look}; +pub use paint::{ + HandleLook, MarkerLook, ResetMarkLook, ResizeLineLook, RuleKind, RuleLook, RuleWidth, ScrollBarKind, ScrollBarLook, resize_line_look, +}; pub(crate) use paint::{min_thumb, scroll_bar_look}; pub use replacements::{DuplicateStyle, StyleReplacements}; pub use span::Span; diff --git a/vendor/hayro-jbig2/src/arithmetic_decoder.rs b/vendor/hayro-jbig2/src/arithmetic_decoder.rs index 8e6adfb5a..a4e81e477 100644 --- a/vendor/hayro-jbig2/src/arithmetic_decoder.rs +++ b/vendor/hayro-jbig2/src/arithmetic_decoder.rs @@ -22,13 +22,7 @@ pub(crate) struct ArithmeticDecoder<'a> { impl<'a> ArithmeticDecoder<'a> { pub(crate) fn new(data: &'a [u8]) -> Self { - let mut decoder = ArithmeticDecoder { - data, - c: 0, - a: 0, - base_pointer: 0, - shift_count: 0, - }; + let mut decoder = ArithmeticDecoder { data, c: 0, a: 0, base_pointer: 0, shift_count: 0 }; decoder.initialize(); @@ -65,18 +59,12 @@ impl<'a> ArithmeticDecoder<'a> { self.shift_count = 8; } else { self.base_pointer += 1; - self.c = self - .c - .wrapping_add(0xfe00) - .wrapping_sub((self.current_byte() as u32) << 9); + self.c = self.c.wrapping_add(0xfe00).wrapping_sub((self.current_byte() as u32) << 9); self.shift_count = 7; } } else { self.base_pointer += 1; - self.c = self - .c - .wrapping_add(0xff00) - .wrapping_sub((self.current_byte() as u32) << 8); + self.c = self.c.wrapping_add(0xff00).wrapping_sub((self.current_byte() as u32) << 8); self.shift_count = 8; } } @@ -285,10 +273,7 @@ impl<'a> ArithmeticDecoder<'a> { #[inline(always)] fn next_byte(&self) -> u8 { - self.data - .get((self.base_pointer + 1) as usize) - .copied() - .unwrap_or(0xFF) + self.data.get((self.base_pointer + 1) as usize).copied().unwrap_or(0xFF) } } diff --git a/vendor/hayro-jbig2/src/bitmap.rs b/vendor/hayro-jbig2/src/bitmap.rs index a40083145..a4efad5c6 100644 --- a/vendor/hayro-jbig2/src/bitmap.rs +++ b/vendor/hayro-jbig2/src/bitmap.rs @@ -121,13 +121,7 @@ impl Bitmap { } /// Create a new bitmap with full configuration. - pub(crate) fn new_with( - width: u32, - height: u32, - x_location: u32, - y_location: u32, - default_pixel: bool, - ) -> Result { + pub(crate) fn new_with(width: u32, height: u32, x_location: u32, y_location: u32, default_pixel: bool) -> Result { if width > MAX_DIMENSION || height > MAX_DIMENSION { bail!(OverflowError::BitmapLimit); } @@ -139,14 +133,7 @@ impl Bitmap { let stride = width.div_ceil(WORD_BITS); let default_word: Word = if default_pixel { !0 } else { 0 }; let data = vec![default_word; stride as usize * height as usize]; - let mut bitmap = Self { - width, - height, - stride, - data, - x_location, - y_location, - }; + let mut bitmap = Self { width, height, stride, data, x_location, y_location }; if default_pixel { bitmap.clear_padding(); } @@ -172,12 +159,7 @@ impl Bitmap { } } - pub(crate) fn reinitialize( - &mut self, - width: u32, - height: u32, - default_pixel: bool, - ) -> Result<()> { + pub(crate) fn reinitialize(&mut self, width: u32, height: u32, default_pixel: bool) -> Result<()> { check_page_size(width, height)?; let stride = width.div_ceil(WORD_BITS); @@ -188,8 +170,7 @@ impl Bitmap { self.x_location = 0; self.y_location = 0; self.data.clear(); - self.data - .resize(stride as usize * height as usize, default_word); + self.data.resize(stride as usize * height as usize, default_word); if default_pixel { self.clear_padding(); } @@ -274,11 +255,7 @@ impl Bitmap { let bit_start = px_start - word_start_x; let bit_end = px_end - word_start_x; - let mask: Word = if bit_end == WORD_BITS { - !0 >> bit_start - } else { - (!0 >> bit_start) & !(!0 >> bit_end) - }; + let mask: Word = if bit_end == WORD_BITS { !0 >> bit_start } else { (!0 >> bit_start) & !(!0 >> bit_end) }; let src_x_for_range = src_x_start + (px_start - dest_x_start); let src_word_idx = src_x_for_range / WORD_BITS; @@ -287,11 +264,8 @@ impl Bitmap { let src_word1 = other.get_word(src_y, src_word_idx); let src_word2 = other.get_word(src_y, src_word_idx + 1); - let src_raw = if src_bit_offset == 0 { - src_word1 - } else { - (src_word1 << src_bit_offset) | (src_word2 >> (WORD_BITS - src_bit_offset)) - }; + let src_raw = + if src_bit_offset == 0 { src_word1 } else { (src_word1 << src_bit_offset) | (src_word2 >> (WORD_BITS - src_bit_offset)) }; let src_aligned = src_raw >> bit_start; let dest_idx = (dest_y * self.stride + word_idx) as usize; @@ -367,25 +341,10 @@ mod pdfcraft_limit_tests { #[test] fn a_bitmap_past_its_bounds_is_refused_by_a_limit() { let limit = Err(DecodeError::Overflow(OverflowError::BitmapLimit)); - assert_eq!( - Bitmap::new(MAX_DIMENSION + 1, 1).map(|_| ()), - limit, - "a side" - ); - assert_eq!( - Bitmap::new(1, MAX_DIMENSION + 1).map(|_| ()), - limit, - "the other" - ); + assert_eq!(Bitmap::new(MAX_DIMENSION + 1, 1).map(|_| ()), limit, "a side"); + assert_eq!(Bitmap::new(1, MAX_DIMENSION + 1).map(|_| ()), limit, "the other"); // 2^28 + 2^14 pixels, each side within its bound. - assert_eq!( - Bitmap::new(1 << 14, (1 << 14) + 1).map(|_| ()), - limit, - "the pixels" - ); - assert!( - Bitmap::new(1 << 14, 1 << 14).is_ok(), - "2^28 pixels are within it" - ); + assert_eq!(Bitmap::new(1 << 14, (1 << 14) + 1).map(|_| ()), limit, "the pixels"); + assert!(Bitmap::new(1 << 14, 1 << 14).is_ok(), "2^28 pixels are within it"); } } diff --git a/vendor/hayro-jbig2/src/decode/generic.rs b/vendor/hayro-jbig2/src/decode/generic.rs index a788163f2..dc23eff04 100644 --- a/vendor/hayro-jbig2/src/decode/generic.rs +++ b/vendor/hayro-jbig2/src/decode/generic.rs @@ -1,8 +1,6 @@ //! Generic region segment parsing and decoding (7.4.6, 6.2). -use super::{ - AdaptiveTemplatePixel, RegionBitmap, RegionSegmentInfo, Template, parse_region_segment_info, -}; +use super::{AdaptiveTemplatePixel, RegionBitmap, RegionSegmentInfo, Template, parse_region_segment_info}; use crate::ScratchBuffers; use crate::arithmetic_decoder::{ArithmeticDecoder, ArithmeticDecoderContext}; use crate::bitmap::{Bitmap, WORD_BITS, WORD_SHIFT, Word}; @@ -10,31 +8,16 @@ use crate::error::{ParseError, RegionError, Result, TemplateError, bail}; use crate::reader::Reader; /// Generic region decoding procedure (6.2). -pub(crate) fn decode( - header: &GenericRegionHeader<'_>, - ctx: &mut ScratchBuffers, -) -> Result { - let mut bitmap = Bitmap::new_with( - header.region_info.width, - header.region_info.height, - header.region_info.x_location, - header.region_info.y_location, - false, - )?; +pub(crate) fn decode(header: &GenericRegionHeader<'_>, ctx: &mut ScratchBuffers) -> Result { + let mut bitmap = + Bitmap::new_with(header.region_info.width, header.region_info.height, header.region_info.x_location, header.region_info.y_location, false)?; decode_into(header, &mut bitmap, ctx)?; - Ok(RegionBitmap { - bitmap, - combination_operator: header.region_info.combination_operator, - }) + Ok(RegionBitmap { bitmap, combination_operator: header.region_info.combination_operator }) } -pub(crate) fn decode_into( - header: &GenericRegionHeader<'_>, - bitmap: &mut Bitmap, - ctx: &mut ScratchBuffers, -) -> Result<()> { +pub(crate) fn decode_into(header: &GenericRegionHeader<'_>, bitmap: &mut Bitmap, ctx: &mut ScratchBuffers) -> Result<()> { let data = header.data; if header.mmr { @@ -43,20 +26,10 @@ pub(crate) fn decode_into( } else { let mut decoder = ArithmeticDecoder::new(data); ctx.contexts.clear(); - ctx.contexts.resize( - 1 << header.template.context_bits(), - ArithmeticDecoderContext::default(), - ); + ctx.contexts.resize(1 << header.template.context_bits(), ArithmeticDecoderContext::default()); // "6.2.5 Decoding using a template and arithmetic coding" - decode_bitmap_arithmetic_coding( - bitmap, - &mut decoder, - &mut ctx.contexts, - header.template, - header.tpgdon, - &header.adaptive_template_pixels, - )?; + decode_bitmap_arithmetic_coding(bitmap, &mut decoder, &mut ctx.contexts, header.template, header.tpgdon, &header.adaptive_template_pixels)?; } Ok(()) @@ -74,21 +47,15 @@ pub(crate) struct GenericRegionHeader<'a> { } /// Parse a generic region segment header (7.4.6.1). -pub(crate) fn parse<'a>( - reader: &mut Reader<'a>, - had_unknown_length: bool, -) -> Result> { +pub(crate) fn parse<'a>(reader: &mut Reader<'a>, had_unknown_length: bool) -> Result> { let mut region_info = parse_region_segment_info(reader)?; let flags = reader.read_byte().ok_or(ParseError::UnexpectedEof)?; let mmr = flags & 0x01 != 0; let template = Template::from_byte(flags >> 1); let tpgdon = flags & 0x08 != 0; let ext_template = flags & 0x10 != 0; - let adaptive_template_pixels = if mmr { - [AdaptiveTemplatePixel::default(); 4] - } else { - parse_adaptive_template_pixels(reader, template, ext_template)? - }; + let adaptive_template_pixels = + if mmr { [AdaptiveTemplatePixel::default(); 4] } else { parse_adaptive_template_pixels(reader, template, ext_template)? }; let mut data = reader.tail().ok_or(ParseError::UnexpectedEof)?; // "As a special case, as noted in 7.2.7, an immediate generic region segment @@ -109,14 +76,7 @@ pub(crate) fn parse<'a>( data = head; } - Ok(GenericRegionHeader { - region_info, - mmr, - template, - tpgdon, - adaptive_template_pixels, - data, - }) + Ok(GenericRegionHeader { region_info, mmr, template, tpgdon, adaptive_template_pixels, data }) } /// Parse adaptive template pixel positions (7.4.6.3). @@ -185,14 +145,7 @@ pub(crate) fn decode_bitmap_mmr(bitmap: &mut Bitmap, data: &[u8]) -> Result BitmapDecoder<'a> { fn new(bitmap: &'a mut Bitmap) -> Self { - Self { - bitmap, - x: 0, - y: 0, - row_start: 0, - buf: 0, - buf_len: 0, - } + Self { bitmap, x: 0, y: 0, row_start: 0, buf: 0, buf_len: 0 } } #[inline] @@ -252,8 +205,7 @@ pub(crate) fn decode_bitmap_mmr(bitmap: &mut Bitmap, data: &[u8]) -> Result first_full { @@ -261,8 +213,7 @@ pub(crate) fn decode_bitmap_mmr(bitmap: &mut Bitmap, data: &[u8]) -> Result Result 0 { let stride = bitmap.stride as usize; let src = (y as usize - 1) * stride; - bitmap - .data - .copy_within(src..src + stride, y as usize * stride); + bitmap.data.copy_within(src..src + stride, y as usize * stride); } } else { // "d) If LTP = 0 then, from left to right, decode each pixel of the @@ -390,81 +338,33 @@ pub(crate) fn decode_bitmap_arithmetic_coding( if ctx_gatherer.use_default_at { match template { - Template::Template0 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template0_default - ), - Template::Template1 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template1_default - ), - Template::Template2 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template2_default - ), - Template::Template3 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template3_default - ), + Template::Template0 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template0_default) + } + Template::Template1 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template1_default) + } + Template::Template2 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template2_default) + } + Template::Template3 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template3_default) + } } } else { match template { - Template::Template0 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template0_custom - ), - Template::Template1 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template1_custom - ), - Template::Template2 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template2_custom - ), - Template::Template3 => decode_loop!( - bitmap, - decoder, - contexts, - &mut ctx_gatherer, - tpgdon, - sltp_context, - ContextGatherer::gather_template3_custom - ), + Template::Template0 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template0_custom) + } + Template::Template1 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template1_custom) + } + Template::Template2 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template2_custom) + } + Template::Template3 => { + decode_loop!(bitmap, decoder, contexts, &mut ctx_gatherer, tpgdon, sltp_context, ContextGatherer::gather_template3_custom) + } } } @@ -508,18 +408,7 @@ impl<'a> ContextGatherer<'a> { } } }; - Self { - template, - at_pixels, - use_default_at, - max_right, - cur_y: 0, - buf_m2: 0, - buf_m1: 0, - buf_cur: 0, - cur_x: 0, - ctx: 0, - } + Self { template, at_pixels, use_default_at, max_right, cur_y: 0, buf_m2: 0, buf_m1: 0, buf_cur: 0, cur_x: 0, ctx: 0 } } const SHIFT_MASK_T0: u16 = 0b0110_0011_1100_1110; @@ -536,26 +425,14 @@ impl<'a> ContextGatherer<'a> { self.cur_y = y; self.cur_x = 0; - self.buf_m2 = if y >= 2 { - Self::load_word(bitmap, y - 2, 0) - } else { - 0 - }; - self.buf_m1 = if y >= 1 { - Self::load_word(bitmap, y - 1, 0) - } else { - 0 - }; + self.buf_m2 = if y >= 2 { Self::load_word(bitmap, y - 2, 0) } else { 0 }; + self.buf_m1 = if y >= 1 { Self::load_word(bitmap, y - 1, 0) } else { 0 }; self.buf_cur = 0; // Start initializing the contexts. Note that this won't load all initial // pixels yet, those will only be loaded after our first call to `gather`. // See 6.2.5.3 for the pixel positions. - self.ctx = if self.use_default_at { - self.init_context_default() - } else { - self.init_context_custom() - }; + self.ctx = if self.use_default_at { self.init_context_default() } else { self.init_context_custom() }; } #[inline] @@ -563,15 +440,12 @@ impl<'a> ContextGatherer<'a> { match self.template { Template::Template0 => { let m2 = Self::get_buf_pixel(self.buf_m2, 0); - let m1 = (Self::get_buf_pixel(self.buf_m1, 0) << 1) - | Self::get_buf_pixel(self.buf_m1, 1); + let m1 = (Self::get_buf_pixel(self.buf_m1, 0) << 1) | Self::get_buf_pixel(self.buf_m1, 1); (m2 << 12) | (m1 << 5) } Template::Template1 => { - let m2 = (Self::get_buf_pixel(self.buf_m2, 0) << 1) - | Self::get_buf_pixel(self.buf_m2, 1); - let m1 = (Self::get_buf_pixel(self.buf_m1, 0) << 1) - | Self::get_buf_pixel(self.buf_m1, 1); + let m2 = (Self::get_buf_pixel(self.buf_m2, 0) << 1) | Self::get_buf_pixel(self.buf_m2, 1); + let m1 = (Self::get_buf_pixel(self.buf_m1, 0) << 1) | Self::get_buf_pixel(self.buf_m1, 1); (m2 << 9) | (m1 << 4) } Template::Template2 => { @@ -604,14 +478,9 @@ impl<'a> ContextGatherer<'a> { | (Self::get_buf_pixel(self.buf_m1, 2) << 3) } Template::Template2 => { - (Self::get_buf_pixel(self.buf_m2, 0) << 7) - | (Self::get_buf_pixel(self.buf_m1, 0) << 3) - | (Self::get_buf_pixel(self.buf_m1, 1) << 2) - } - Template::Template3 => { - (Self::get_buf_pixel(self.buf_m1, 0) << 5) - | (Self::get_buf_pixel(self.buf_m1, 1) << 4) + (Self::get_buf_pixel(self.buf_m2, 0) << 7) | (Self::get_buf_pixel(self.buf_m1, 0) << 3) | (Self::get_buf_pixel(self.buf_m1, 1) << 2) } + Template::Template3 => (Self::get_buf_pixel(self.buf_m1, 0) << 5) | (Self::get_buf_pixel(self.buf_m1, 1) << 4), } } @@ -631,11 +500,7 @@ impl<'a> ContextGatherer<'a> { #[inline] pub(crate) fn get_buf_pixel(buf: Word, pos: u32) -> u16 { - if pos < WORD_BITS { - ((buf >> (WORD_SHIFT - pos)) & 1) as u16 - } else { - 0 - } + if pos < WORD_BITS { ((buf >> (WORD_SHIFT - pos)) & 1) as u16 } else { 0 } } #[inline(always)] @@ -643,16 +508,8 @@ impl<'a> ContextGatherer<'a> { if x + self.max_right >= self.cur_x + WORD_BITS { let new_start = x.saturating_sub(4); self.cur_x = new_start; - self.buf_m2 = if self.cur_y >= 2 { - Self::load_word(bitmap, self.cur_y - 2, new_start) - } else { - 0 - }; - self.buf_m1 = if self.cur_y >= 1 { - Self::load_word(bitmap, self.cur_y - 1, new_start) - } else { - 0 - }; + self.buf_m2 = if self.cur_y >= 2 { Self::load_word(bitmap, self.cur_y - 2, new_start) } else { 0 }; + self.buf_m1 = if self.cur_y >= 1 { Self::load_word(bitmap, self.cur_y - 1, new_start) } else { 0 }; self.buf_cur = Self::load_word(bitmap, self.cur_y, new_start); } } @@ -688,11 +545,7 @@ impl<'a> ContextGatherer<'a> { let new_pixels = (Self::get_buf_pixel(self.buf_m2, bx + 2) << 9) | (Self::get_buf_pixel(self.buf_m1, bx + 2) << 4) | Self::get_buf_pixel(self.buf_cur, bx.wrapping_sub(1)) - | ((bitmap.get_pixel( - (xi + self.at_pixels[0].x as i32) as u32, - (yi + self.at_pixels[0].y as i32) as u32, - ) as u16) - << 3); + | ((bitmap.get_pixel((xi + self.at_pixels[0].x as i32) as u32, (yi + self.at_pixels[0].y as i32) as u32) as u16) << 3); self.ctx = ((self.ctx << 1) & Self::SHIFT_MASK_T1) | new_pixels; self.ctx @@ -707,11 +560,7 @@ impl<'a> ContextGatherer<'a> { let new_pixels = (Self::get_buf_pixel(self.buf_m2, bx + 1) << 7) | (Self::get_buf_pixel(self.buf_m1, bx + 1) << 3) | Self::get_buf_pixel(self.buf_cur, bx.wrapping_sub(1)) - | ((bitmap.get_pixel( - (xi + self.at_pixels[0].x as i32) as u32, - (yi + self.at_pixels[0].y as i32) as u32, - ) as u16) - << 2); + | ((bitmap.get_pixel((xi + self.at_pixels[0].x as i32) as u32, (yi + self.at_pixels[0].y as i32) as u32) as u16) << 2); self.ctx = ((self.ctx << 1) & Self::SHIFT_MASK_T2) | new_pixels; self.ctx @@ -725,11 +574,7 @@ impl<'a> ContextGatherer<'a> { let new_pixels = (Self::get_buf_pixel(self.buf_m1, bx + 1) << 5) | Self::get_buf_pixel(self.buf_cur, bx.wrapping_sub(1)) - | ((bitmap.get_pixel( - (xi + self.at_pixels[0].x as i32) as u32, - (yi + self.at_pixels[0].y as i32) as u32, - ) as u16) - << 4); + | ((bitmap.get_pixel((xi + self.at_pixels[0].x as i32) as u32, (yi + self.at_pixels[0].y as i32) as u32) as u16) << 4); self.ctx = ((self.ctx << 1) & Self::SHIFT_MASK_T3) | new_pixels; self.ctx @@ -771,8 +616,7 @@ impl<'a> ContextGatherer<'a> { #[inline(always)] pub(crate) fn gather_template3_default(&mut self, _bitmap: &Bitmap, x: u32) -> u16 { let bx = x - self.cur_x; - let new_pixels = (Self::get_buf_pixel(self.buf_m1, bx + 2) << 4) - | Self::get_buf_pixel(self.buf_cur, bx.wrapping_sub(1)); + let new_pixels = (Self::get_buf_pixel(self.buf_m1, bx + 2) << 4) | Self::get_buf_pixel(self.buf_cur, bx.wrapping_sub(1)); self.ctx = ((self.ctx << 1) & Self::SHIFT_MASK_T3_DEFAULT) | new_pixels; self.ctx diff --git a/vendor/hayro-jbig2/src/decode/generic_refinement.rs b/vendor/hayro-jbig2/src/decode/generic_refinement.rs index cd730fd93..8f03e14f9 100644 --- a/vendor/hayro-jbig2/src/decode/generic_refinement.rs +++ b/vendor/hayro-jbig2/src/decode/generic_refinement.rs @@ -2,10 +2,7 @@ use alloc::vec::Vec; -use super::{ - AdaptiveTemplatePixel, RefinementTemplate, RegionBitmap, RegionSegmentInfo, - parse_refinement_at_pixels, parse_region_segment_info, -}; +use super::{AdaptiveTemplatePixel, RefinementTemplate, RegionBitmap, RegionSegmentInfo, parse_refinement_at_pixels, parse_region_segment_info}; use crate::ScratchBuffers; use crate::arithmetic_decoder::{ArithmeticDecoder, ArithmeticDecoderContext}; use crate::bitmap::{Bitmap, WORD_BITS, WORD_SHIFT, Word}; @@ -14,25 +11,13 @@ use crate::error::{ParseError, RegionError, Result, bail}; use crate::reader::Reader; /// Generic refinement region decoding procedure (6.3). -pub(crate) fn decode( - header: &GenericRefinementRegionHeader<'_>, - reference: &Bitmap, - ctx: &mut ScratchBuffers, -) -> Result { - let mut region = Bitmap::new_with( - header.region_info.width, - header.region_info.height, - header.region_info.x_location, - header.region_info.y_location, - false, - )?; +pub(crate) fn decode(header: &GenericRefinementRegionHeader<'_>, reference: &Bitmap, ctx: &mut ScratchBuffers) -> Result { + let mut region = + Bitmap::new_with(header.region_info.width, header.region_info.height, header.region_info.x_location, header.region_info.y_location, false)?; decode_into(header, reference, &mut region, ctx)?; - Ok(RegionBitmap { - bitmap: region, - combination_operator: header.region_info.combination_operator, - }) + Ok(RegionBitmap { bitmap: region, combination_operator: header.region_info.combination_operator }) } /// Decode a generic refinement region directly into an existing bitmap. @@ -62,8 +47,7 @@ pub(crate) fn decode_into( let mut decoder = ArithmeticDecoder::new(data); let num_context_bits = header.template.context_bits(); ctx.contexts.clear(); - ctx.contexts - .resize(1 << num_context_bits, ArithmeticDecoderContext::default()); + ctx.contexts.resize(1 << num_context_bits, ArithmeticDecoderContext::default()); decode_bitmap( &mut decoder, @@ -96,28 +80,14 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result bool { - at_pixels.len() >= 2 - && at_pixels[0].x == -1 - && at_pixels[0].y == -1 - && at_pixels[1].x == -1 - && at_pixels[1].y == -1 + at_pixels.len() >= 2 && at_pixels[0].x == -1 && at_pixels[0].y == -1 && at_pixels[1].x == -1 && at_pixels[1].y == -1 } pub(crate) struct RefinementContextGatherer<'a> { @@ -142,14 +112,8 @@ const SHIFT_MASK_T0_CUSTOM: u16 = 0b0_1000_1011_0110; const SHIFT_MASK_T1: u16 = 0b11_0001_1010; impl<'a> RefinementContextGatherer<'a> { - pub(crate) fn new( - template: RefinementTemplate, - at_pixels: &'a [AdaptiveTemplatePixel], - reference_dx: i32, - reference_dy: i32, - ) -> Self { - let use_default_at = - template == RefinementTemplate::Template0 && has_default_at_pixels(at_pixels); + pub(crate) fn new(template: RefinementTemplate, at_pixels: &'a [AdaptiveTemplatePixel], reference_dx: i32, reference_dy: i32) -> Self { + let use_default_at = template == RefinementTemplate::Template0 && has_default_at_pixels(at_pixels); Self { template, at_pixels, @@ -178,11 +142,7 @@ impl<'a> RefinementContextGatherer<'a> { let ref_x0 = self.reference_dx.wrapping_neg() as u32; self.reg_cur_x = 0; - self.reg_m1 = if y >= 1 { - ContextGatherer::load_word(region, y - 1, 0) - } else { - 0 - }; + self.reg_m1 = if y >= 1 { ContextGatherer::load_word(region, y - 1, 0) } else { 0 }; self.reg_cur = 0; // PdfCraft patch: the buffers start a column left of the reference column the row starts @@ -193,16 +153,10 @@ impl<'a> RefinementContextGatherer<'a> { // below −31, which a refined text instance has from a narrower bitmap or an RDX below −31, // and a refined symbol from such an RDX). The region decoded to other pixels than were // coded, or failed. - self.ref_cur_x = self - .reference_dx - .checked_neg() - .and_then(|column| u32::try_from(column).ok()) - .map_or(0, |column| column.saturating_sub(1)); - self.ref_m1 = - ContextGatherer::load_word(reference, ref_y.wrapping_sub(1) as u32, self.ref_cur_x); + self.ref_cur_x = self.reference_dx.checked_neg().and_then(|column| u32::try_from(column).ok()).map_or(0, |column| column.saturating_sub(1)); + self.ref_m1 = ContextGatherer::load_word(reference, ref_y.wrapping_sub(1) as u32, self.ref_cur_x); self.ref_cur = ContextGatherer::load_word(reference, ref_y as u32, self.ref_cur_x); - self.ref_p1 = - ContextGatherer::load_word(reference, ref_y.wrapping_add(1) as u32, self.ref_cur_x); + self.ref_p1 = ContextGatherer::load_word(reference, ref_y.wrapping_add(1) as u32, self.ref_cur_x); self.ctx = match self.template { RefinementTemplate::Template1 => { @@ -225,13 +179,7 @@ impl<'a> RefinementContextGatherer<'a> { let ref_p1_m1 = ContextGatherer::get_buf_pixel(self.ref_p1, rbx.wrapping_sub(1)); let ref_p1_0 = ContextGatherer::get_buf_pixel(self.ref_p1, rbx); - (reg_m1_0 << 10) - | (ref_m1_m1 << 7) - | (ref_m1_0 << 6) - | (ref_cur_m1 << 4) - | (ref_cur_0 << 3) - | (ref_p1_m1 << 1) - | ref_p1_0 + (reg_m1_0 << 10) | (ref_m1_m1 << 7) | (ref_m1_0 << 6) | (ref_cur_m1 << 4) | (ref_cur_0 << 3) | (ref_p1_m1 << 1) | ref_p1_0 } RefinementTemplate::Template0 => { let rbx = ref_x0.wrapping_sub(self.ref_cur_x); @@ -241,12 +189,7 @@ impl<'a> RefinementContextGatherer<'a> { let ref_cur_0 = ContextGatherer::get_buf_pixel(self.ref_cur, rbx); let ref_p1_m1 = ContextGatherer::get_buf_pixel(self.ref_p1, rbx.wrapping_sub(1)); let ref_p1_0 = ContextGatherer::get_buf_pixel(self.ref_p1, rbx); - (reg_m1_0 << 10) - | (ref_m1_0 << 6) - | (ref_cur_m1 << 4) - | (ref_cur_0 << 3) - | (ref_p1_m1 << 1) - | ref_p1_0 + (reg_m1_0 << 10) | (ref_m1_0 << 6) | (ref_cur_m1 << 4) | (ref_cur_0 << 3) | (ref_p1_m1 << 1) | ref_p1_0 } }; } @@ -256,11 +199,7 @@ impl<'a> RefinementContextGatherer<'a> { if x + 1 >= self.reg_cur_x + WORD_BITS { let new_start = x.saturating_sub(1); self.reg_cur_x = new_start; - self.reg_m1 = if self.reg_y >= 1 { - ContextGatherer::load_word(region, self.reg_y - 1, new_start) - } else { - 0 - }; + self.reg_m1 = if self.reg_y >= 1 { ContextGatherer::load_word(region, self.reg_y - 1, new_start) } else { 0 }; self.reg_cur = ContextGatherer::load_word(region, self.reg_y, new_start); } @@ -278,11 +217,9 @@ impl<'a> RefinementContextGatherer<'a> { let new_start = ref_x.saturating_sub(1); let ref_y = (self.reg_y as i32).wrapping_sub(self.reference_dy); self.ref_cur_x = new_start; - self.ref_m1 = - ContextGatherer::load_word(reference, ref_y.wrapping_sub(1) as u32, new_start); + self.ref_m1 = ContextGatherer::load_word(reference, ref_y.wrapping_sub(1) as u32, new_start); self.ref_cur = ContextGatherer::load_word(reference, ref_y as u32, new_start); - self.ref_p1 = - ContextGatherer::load_word(reference, ref_y.wrapping_add(1) as u32, new_start); + self.ref_p1 = ContextGatherer::load_word(reference, ref_y.wrapping_add(1) as u32, new_start); } } @@ -363,16 +300,10 @@ impl<'a> RefinementContextGatherer<'a> { let at1 = self.at_pixels[0]; let at2 = self.at_pixels[1]; - let new_pixels = ((region.get_pixel((xi + at1.x as i32) as u32, (yi + at1.y as i32) as u32) - as u16) - << 12) + let new_pixels = ((region.get_pixel((xi + at1.x as i32) as u32, (yi + at1.y as i32) as u32) as u16) << 12) | (ContextGatherer::get_buf_pixel(self.reg_m1, bx + 1) << 10) | (ContextGatherer::get_buf_pixel(self.reg_cur, bx.wrapping_sub(1)) << 9) - | ((reference.get_pixel( - ref_x_i.wrapping_add(at2.x as i32) as u32, - ref_y.wrapping_add(at2.y as i32) as u32, - ) as u16) - << 8) + | ((reference.get_pixel(ref_x_i.wrapping_add(at2.x as i32) as u32, ref_y.wrapping_add(at2.y as i32) as u32) as u16) << 8) | (ContextGatherer::get_buf_pixel(self.ref_m1, rbx.wrapping_add(1)) << 6) | (ContextGatherer::get_buf_pixel(self.ref_cur, rbx.wrapping_add(1)) << 3) | ContextGatherer::get_buf_pixel(self.ref_p1, rbx.wrapping_add(1)); @@ -478,12 +409,7 @@ pub(crate) fn decode_bitmap( }}; } - let mut gatherer = RefinementContextGatherer::new( - gr_template, - adaptive_template_pixels, - reference_dx, - reference_dy, - ); + let mut gatherer = RefinementContextGatherer::new(gr_template, adaptive_template_pixels, reference_dx, reference_dy); // Context for SLTP depends on template (Figures 14, 15). let sltp_context: u16 = match gr_template { @@ -492,24 +418,13 @@ pub(crate) fn decode_bitmap( }; match gr_template { - RefinementTemplate::Template0 if gatherer.use_default_at => refinement_decode_loop!( - &mut gatherer, - tpgron, - sltp_context, - RefinementContextGatherer::gather_template0_default - ), - RefinementTemplate::Template0 => refinement_decode_loop!( - &mut gatherer, - tpgron, - sltp_context, - RefinementContextGatherer::gather_template0_custom - ), - RefinementTemplate::Template1 => refinement_decode_loop!( - &mut gatherer, - tpgron, - sltp_context, - RefinementContextGatherer::gather_template1 - ), + RefinementTemplate::Template0 if gatherer.use_default_at => { + refinement_decode_loop!(&mut gatherer, tpgron, sltp_context, RefinementContextGatherer::gather_template0_default) + } + RefinementTemplate::Template0 => { + refinement_decode_loop!(&mut gatherer, tpgron, sltp_context, RefinementContextGatherer::gather_template0_custom) + } + RefinementTemplate::Template1 => refinement_decode_loop!(&mut gatherer, tpgron, sltp_context, RefinementContextGatherer::gather_template1), } Ok(()) diff --git a/vendor/hayro-jbig2/src/decode/halftone.rs b/vendor/hayro-jbig2/src/decode/halftone.rs index 10000f801..529e8c367 100644 --- a/vendor/hayro-jbig2/src/decode/halftone.rs +++ b/vendor/hayro-jbig2/src/decode/halftone.rs @@ -13,27 +13,14 @@ use crate::gray_scale::{GrayScaleParams, decode_gray_scale_image}; use crate::reader::Reader; /// Decode a halftone region segment (7.4.5.2, 6.6). -pub(crate) fn decode( - header: &HalftoneRegionHeader<'_>, - pattern_dict: &PatternDictionary, - ctx: &mut ScratchBuffers, -) -> Result { +pub(crate) fn decode(header: &HalftoneRegionHeader<'_>, pattern_dict: &PatternDictionary, ctx: &mut ScratchBuffers) -> Result { let region = &header.region_info; - let mut htreg = Bitmap::new_with( - region.width, - region.height, - region.x_location, - region.y_location, - header.flags.initial_pixel_color, - )?; + let mut htreg = Bitmap::new_with(region.width, region.height, region.x_location, region.y_location, header.flags.initial_pixel_color)?; decode_into(header, pattern_dict, &mut htreg, ctx)?; - Ok(RegionBitmap { - bitmap: htreg, - combination_operator: region.combination_operator, - }) + Ok(RegionBitmap { bitmap: htreg, combination_operator: region.combination_operator }) } pub(crate) fn decode_into( @@ -42,11 +29,7 @@ pub(crate) fn decode_into( htreg: &mut Bitmap, ctx: &mut ScratchBuffers, ) -> Result<()> { - let skip_bitmap = if header.flags.enable_skip { - Some(compute_skip_bitmap(header, pattern_dict, htreg)?) - } else { - None - }; + let skip_bitmap = if header.flags.enable_skip { Some(compute_skip_bitmap(header, pattern_dict, htreg)?) } else { None }; let bits_per_pixel = bits_per_pixel(pattern_dict); @@ -85,10 +68,7 @@ pub(crate) fn work(header: &HalftoneRegionHeader<'_>, patterns: &PatternDictiona /// "3) Set HBPP to ⌈log₂(HNUMPATS)⌉." (6.6.5) fn bits_per_pixel(patterns: &PatternDictionary) -> u32 { - (patterns.patterns.len() as u32) - .saturating_sub(1) - .checked_ilog2() - .map_or(1, |n| n + 1) + (patterns.patterns.len() as u32).saturating_sub(1).checked_ilog2().map_or(1, |n| n + 1) } /// Parse a halftone region segment header (7.4.5.1). @@ -101,13 +81,7 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result> 4)?; let initial_pixel_color = flags_byte & 0x80 != 0; - let flags = HalftoneRegionFlags { - mmr, - template, - enable_skip, - combination_operator, - initial_pixel_color, - }; + let flags = HalftoneRegionFlags { mmr, template, enable_skip, combination_operator, initial_pixel_color }; let grid_width = reader.read_u32().ok_or(ParseError::UnexpectedEof)?; let grid_height = reader.read_u32().ok_or(ParseError::UnexpectedEof)?; @@ -135,20 +109,11 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result, - pattern_dict: &PatternDictionary, - htreg: &Bitmap, -) -> Result> { +fn compute_skip_bitmap(header: &HalftoneRegionHeader<'_>, pattern_dict: &PatternDictionary, htreg: &Bitmap) -> Result> { let grid = &header.grid_position_and_size; let pattern_width = pattern_dict.pattern_width as i32; let pattern_height = pattern_dict.pattern_height as i32; @@ -243,9 +204,7 @@ fn compute_skip_bitmap( let region_height = htreg.height as i32; let stride = grid.width.div_ceil(32); - let len = stride - .checked_mul(grid.height) - .ok_or(OverflowError::BitmapDimension)? as usize; + let len = stride.checked_mul(grid.height).ok_or(OverflowError::BitmapDimension)? as usize; let mut hskip = vec![0_u32; len]; let mut coords = GridCoords::new(grid, &header.grid_vector); @@ -253,10 +212,7 @@ fn compute_skip_bitmap( for n_g in 0..grid.width { let (x, y) = coords.get(); - let skip = (x + pattern_width <= 0) - || (x >= region_width) - || (y + pattern_height <= 0) - || (y >= region_height); + let skip = (x + pattern_width <= 0) || (x >= region_width) || (y + pattern_height <= 0) || (y >= region_height); if skip { let word_idx = (m_g * stride + n_g / 32) as usize; @@ -273,12 +229,7 @@ fn compute_skip_bitmap( } /// Render patterns into the target region (6.6.5.2). -fn render_patterns( - region: &mut Bitmap, - gi: &[u32], - header: &HalftoneRegionHeader<'_>, - pattern_dict: &PatternDictionary, -) -> Result<()> { +fn render_patterns(region: &mut Bitmap, gi: &[u32], header: &HalftoneRegionHeader<'_>, pattern_dict: &PatternDictionary) -> Result<()> { let grid = &header.grid_position_and_size; let op = header.flags.combination_operator; let pw = pattern_dict.pattern_width; @@ -289,11 +240,7 @@ fn render_patterns( let num_patterns = pattern_dict.patterns.len(); // The original pattern mask has 1s in the top `pw` bits. - let original_mask = if pw >= WORD_BITS { - !0_u32 - } else { - !0_u32 << (WORD_BITS - pw) - }; + let original_mask = if pw >= WORD_BITS { !0_u32 } else { !0_u32 << (WORD_BITS - pw) }; macro_rules! blit_rows { ($data:expr, $shifted:expr, $yu:expr, $first_word:expr, $two:expr, @@ -335,12 +282,11 @@ fn render_patterns( } // Check whether we can use the blit fast path. - let shifted = - if x >= 0 && y >= 0 && x + pw as i32 <= region_w && y + ph as i32 <= region_h { - pattern_dict.shifted_pattern(pattern_index, x as u32 % WORD_BITS) - } else { - None - }; + let shifted = if x >= 0 && y >= 0 && x + pw as i32 <= region_w && y + ph as i32 <= region_h { + pattern_dict.shifted_pattern(pattern_index, x as u32 % WORD_BITS) + } else { + None + }; if let Some(shifted) = shifted { let xu = x as u32; @@ -354,79 +300,28 @@ fn render_patterns( match op { CombinationOperator::Or => { - blit_rows!( - region.data, - shifted, - yu, - first_word, - two, - |d, s| d | s, - |d, s| d | s - ); + blit_rows!(region.data, shifted, yu, first_word, two, |d, s| d | s, |d, s| d | s); } CombinationOperator::Xor => { - blit_rows!( - region.data, - shifted, - yu, - first_word, - two, - |d, s| d ^ s, - |d, s| d ^ s - ); + blit_rows!(region.data, shifted, yu, first_word, two, |d, s| d ^ s, |d, s| d ^ s); } CombinationOperator::And => { let inv_mask0 = !(original_mask >> offset); - let inv_mask1 = if offset == 0 { - !0 - } else { - !(original_mask << (WORD_BITS - offset)) - }; - blit_rows!( - region.data, - shifted, - yu, - first_word, - two, - |d, s| d & (s | inv_mask0), - |d, s| d & (s | inv_mask1) - ); + let inv_mask1 = if offset == 0 { !0 } else { !(original_mask << (WORD_BITS - offset)) }; + blit_rows!(region.data, shifted, yu, first_word, two, |d, s| d & (s | inv_mask0), |d, s| d & (s | inv_mask1)); } CombinationOperator::Replace => { let inv_mask0 = !(original_mask >> offset); - let inv_mask1 = if offset == 0 { - !0 - } else { - !(original_mask << (WORD_BITS - offset)) - }; - blit_rows!( - region.data, - shifted, - yu, - first_word, - two, - |d, s| (d & inv_mask0) | s, - |d, s| (d & inv_mask1) | s - ); + let inv_mask1 = if offset == 0 { !0 } else { !(original_mask << (WORD_BITS - offset)) }; + blit_rows!(region.data, shifted, yu, first_word, two, |d, s| (d & inv_mask0) | s, |d, s| (d & inv_mask1) | s); } CombinationOperator::Xnor => { let mask0 = original_mask >> offset; - let mask1 = if offset == 0 { - 0 - } else { - original_mask << (WORD_BITS - offset) - }; + let mask1 = if offset == 0 { 0 } else { original_mask << (WORD_BITS - offset) }; let inv_mask0 = !mask0; let inv_mask1 = !mask1; - blit_rows!( - region.data, - shifted, - yu, - first_word, - two, - |d, s| (d & inv_mask0) | (!(d ^ s) & mask0), - |d, s| (d & inv_mask1) | (!(d ^ s) & mask1) - ); + blit_rows!(region.data, shifted, yu, first_word, two, |d, s| (d & inv_mask0) | (!(d ^ s) & mask0), |d, s| (d & inv_mask1) + | (!(d ^ s) & mask1)); } } } else { diff --git a/vendor/hayro-jbig2/src/decode/mod.rs b/vendor/hayro-jbig2/src/decode/mod.rs index da9e0eccf..bd72ab71a 100644 --- a/vendor/hayro-jbig2/src/decode/mod.rs +++ b/vendor/hayro-jbig2/src/decode/mod.rs @@ -166,14 +166,7 @@ pub(crate) fn parse_region_segment_info(reader: &mut Reader<'_>) -> Result, -) -> Result> { +pub(crate) fn parse_refinement_at_pixels(reader: &mut Reader<'_>) -> Result> { let x1 = reader.read_byte().ok_or(ParseError::UnexpectedEof)? as i8; let y1 = reader.read_byte().ok_or(ParseError::UnexpectedEof)? as i8; let x2 = reader.read_byte().ok_or(ParseError::UnexpectedEof)? as i8; let y2 = reader.read_byte().ok_or(ParseError::UnexpectedEof)? as i8; - Ok(vec![ - AdaptiveTemplatePixel { x: x1, y: y1 }, - AdaptiveTemplatePixel { x: x2, y: y2 }, - ]) + Ok(vec![AdaptiveTemplatePixel { x: x1, y: y1 }, AdaptiveTemplatePixel { x: x2, y: y2 }]) } /// Template used for refinement arithmetic coding (7.4.7.2). @@ -219,11 +207,7 @@ pub(crate) enum RefinementTemplate { impl RefinementTemplate { pub(crate) fn from_byte(value: u8) -> Self { - if value & 0x01 == 0 { - Template0 - } else { - Template1 - } + if value & 0x01 == 0 { Template0 } else { Template1 } } /// Number of context bits for this template (6.3.5.3). diff --git a/vendor/hayro-jbig2/src/decode/pattern.rs b/vendor/hayro-jbig2/src/decode/pattern.rs index 03d4d8eb8..226774d46 100644 --- a/vendor/hayro-jbig2/src/decode/pattern.rs +++ b/vendor/hayro-jbig2/src/decode/pattern.rs @@ -13,24 +13,15 @@ use alloc::vec::Vec; const MAX_SHIFTED_WORDS: u64 = 1 << 22; /// Decode a pattern dictionary segment (7.4.4.2, 6.7). -pub(crate) fn decode( - header: &PatternDictionaryHeader<'_>, - scratch: &mut ScratchBuffers, - room: u64, -) -> Result { +pub(crate) fn decode(header: &PatternDictionaryHeader<'_>, scratch: &mut ScratchBuffers, room: u64) -> Result { let pattern_width = header.pattern_width as u32; let pattern_height = header.pattern_height as u32; - let num_patterns = header - .num_patterns - .checked_add(1) - .ok_or(OverflowError::BitmapDimension)?; + let num_patterns = header.num_patterns.checked_add(1).ok_or(OverflowError::BitmapDimension)?; // "1) Create a bitmap B_HDC. The height of this bitmap is HDPH. The width // of the bitmap is (GRAYMAX + 1) × HDPW. This bitmap contains all the // patterns concatenated left to right." (6.7.5) - let collective_width = num_patterns - .checked_mul(pattern_width) - .ok_or(OverflowError::BitmapDimension)?; + let collective_width = num_patterns.checked_mul(pattern_width).ok_or(OverflowError::BitmapDimension)?; let mut collective_bitmap = Bitmap::new(collective_width, pattern_height)?; @@ -41,19 +32,13 @@ pub(crate) fn decode( } else { let at_pixels = match header.template { Template::Template0 => [ - AdaptiveTemplatePixel { - x: -(pattern_width as i8), - y: 0, - }, + AdaptiveTemplatePixel { x: -(pattern_width as i8), y: 0 }, AdaptiveTemplatePixel { x: -3, y: -1 }, AdaptiveTemplatePixel { x: 2, y: -2 }, AdaptiveTemplatePixel { x: -2, y: -2 }, ], Template::Template1 | Template::Template2 | Template::Template3 => [ - AdaptiveTemplatePixel { - x: -(pattern_width as i8), - y: 0, - }, + AdaptiveTemplatePixel { x: -(pattern_width as i8), y: 0 }, // Unused. AdaptiveTemplatePixel::default(), AdaptiveTemplatePixel::default(), @@ -63,19 +48,9 @@ pub(crate) fn decode( let mut decoder = ArithmeticDecoder::new(header.data); scratch.contexts.clear(); - scratch.contexts.resize( - 1 << header.template.context_bits(), - ArithmeticDecoderContext::default(), - ); + scratch.contexts.resize(1 << header.template.context_bits(), ArithmeticDecoderContext::default()); - generic::decode_bitmap_arithmetic_coding( - &mut collective_bitmap, - &mut decoder, - &mut scratch.contexts, - header.template, - false, - &at_pixels, - )?; + generic::decode_bitmap_arithmetic_coding(&mut collective_bitmap, &mut decoder, &mut scratch.contexts, header.template, false, &at_pixels)?; } // "3) Set: GRAY = 0" (6.7.5) @@ -101,17 +76,9 @@ pub(crate) fn decode( for w in 0..dst_stride { let s1 = collective_bitmap.data[src_row + w as usize]; - let s2 = collective_bitmap - .data - .get(src_row + w as usize + 1) - .copied() - .unwrap_or(0); + let s2 = collective_bitmap.data.get(src_row + w as usize + 1).copied().unwrap_or(0); - let word: Word = if src_bit_offset == 0 { - s1 - } else { - (s1 << src_bit_offset) | (s2 >> (WORD_BITS - src_bit_offset)) - }; + let word: Word = if src_bit_offset == 0 { s1 } else { (s1 << src_bit_offset) | (s2 >> (WORD_BITS - src_bit_offset)) }; pattern.data[dst_row + w as usize] = word; } @@ -142,9 +109,7 @@ pub(crate) fn decode( // PdfCraft patch: only when the table is small, and fits what the page may still hold // (`room`), so that a speed-up never gets an image refused. It can be left out: // `shifted_pattern` then returns `None` and the patterns are combined the slow way. - let shifted_words = (patterns.len() as u64) - .saturating_mul(32 * 2) - .saturating_mul(u64::from(pattern_height)); + let shifted_words = (patterns.len() as u64).saturating_mul(32 * 2).saturating_mul(u64::from(pattern_height)); let pattern_words = patterns.iter().map(|p| p.words() as u64).fold(0, u64::saturating_add); let shifted_patterns = if pattern_width <= WORD_BITS && pattern_height <= WORD_BITS @@ -172,12 +137,7 @@ pub(crate) fn decode( Vec::new() }; - Ok(PatternDictionary { - patterns, - pattern_width, - pattern_height, - shifted_patterns, - }) + Ok(PatternDictionary { patterns, pattern_width, pattern_height, shifted_patterns }) } /// A decoded pattern dictionary. @@ -234,21 +194,10 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result> 1); - let pattern_width = reader - .read_nonzero_byte() - .ok_or(ParseError::UnexpectedEof)?; - let pattern_height = reader - .read_nonzero_byte() - .ok_or(ParseError::UnexpectedEof)?; + let pattern_width = reader.read_nonzero_byte().ok_or(ParseError::UnexpectedEof)?; + let pattern_height = reader.read_nonzero_byte().ok_or(ParseError::UnexpectedEof)?; let num_patterns = reader.read_u32().ok_or(ParseError::UnexpectedEof)?; let data = reader.tail().ok_or(ParseError::UnexpectedEof)?; - Ok(PatternDictionaryHeader { - mmr, - template, - pattern_width, - pattern_height, - num_patterns, - data, - }) + Ok(PatternDictionaryHeader { mmr, template, pattern_width, pattern_height, num_patterns, data }) } diff --git a/vendor/hayro-jbig2/src/decode/symbol.rs b/vendor/hayro-jbig2/src/decode/symbol.rs index 6eefa0564..96c0c36dd 100644 --- a/vendor/hayro-jbig2/src/decode/symbol.rs +++ b/vendor/hayro-jbig2/src/decode/symbol.rs @@ -7,17 +7,11 @@ use crate::arithmetic_decoder::{ArithmeticDecoder, ArithmeticDecoderContext}; use crate::bitmap::{BITMAP_WORDS, Bitmap, HUFFMAN_LINE_WORK, INTEGER_WORK, WORD_BITS, Word, decode_work}; use crate::decode::generic::{decode_bitmap_mmr, parse_adaptive_template_pixels}; use crate::decode::text::{ - DecodeContext, ReferenceCorner, TextRegionContexts, TextRegionFlags, TextRegionHeader, - TextRegionHuffmanFlags, decode_with, -}; -use crate::decode::{ - AdaptiveTemplatePixel, CombinationOperator, RefinementTemplate, RegionSegmentInfo, Template, - parse_refinement_at_pixels, + DecodeContext, ReferenceCorner, TextRegionContexts, TextRegionFlags, TextRegionHeader, TextRegionHuffmanFlags, decode_with, }; +use crate::decode::{AdaptiveTemplatePixel, CombinationOperator, RefinementTemplate, RegionSegmentInfo, Template, parse_refinement_at_pixels}; use crate::decode::{generic, generic_refinement}; -use crate::error::{ - DecodeError, HuffmanError, OverflowError, ParseError, Result, SymbolError, bail, -}; +use crate::error::{DecodeError, HuffmanError, OverflowError, ParseError, Result, SymbolError, bail}; use crate::huffman_table::{HuffmanTable, StandardHuffmanTables}; use crate::integer_decoder::IntegerDecoder; use crate::reader::Reader; @@ -73,27 +67,17 @@ pub(crate) fn decode( let read_height_class_delta = |ctx: &mut SymbolDecodeContext<'_>| { if ctx.header.flags.use_huffman { - ctx.h_ctx - .height_class_delta_table - .decode(&mut ctx.h_ctx.reader) + ctx.h_ctx.height_class_delta_table.decode(&mut ctx.h_ctx.reader) } else { - Ok(ctx - .a_ctx - .height_class_delta_decoder - .decode(&mut ctx.a_ctx.decoder)) + Ok(ctx.a_ctx.height_class_delta_decoder.decode(&mut ctx.a_ctx.decoder)) } }; let read_symbol_width_delta = |ctx: &mut SymbolDecodeContext<'_>| { if ctx.header.flags.use_huffman { - ctx.h_ctx - .symbol_width_delta_table - .decode(&mut ctx.h_ctx.reader) + ctx.h_ctx.symbol_width_delta_table.decode(&mut ctx.h_ctx.reader) } else { - Ok(ctx - .a_ctx - .symbol_width_delta_decoder - .decode(&mut ctx.a_ctx.decoder)) + Ok(ctx.a_ctx.symbol_width_delta_decoder.decode(&mut ctx.a_ctx.decoder)) } }; @@ -107,13 +91,9 @@ pub(crate) fn decode( height_classes_left -= 1; // PdfCraft patch: see `bitmap::INTEGER_WORK`. A class of no symbols still reads its delta. *ctx.work_left = ctx.work_left.checked_sub(INTEGER_WORK).ok_or(OverflowError::DecodingWork)?; - let height_class_delta = - read_height_class_delta(&mut ctx)?.ok_or(SymbolError::UnexpectedOob)?; + let height_class_delta = read_height_class_delta(&mut ctx)?.ok_or(SymbolError::UnexpectedOob)?; - ctx.height_class_height = ctx - .height_class_height - .checked_add_signed(height_class_delta) - .ok_or(OverflowError::BitmapDimension)?; + ctx.height_class_height = ctx.height_class_height.checked_add_signed(height_class_delta).ok_or(OverflowError::BitmapDimension)?; let mut symbol_width: u32 = 0; ctx.total_width = 0; @@ -127,17 +107,10 @@ pub(crate) fn decode( bail!(SymbolError::TooManySymbols); } - symbol_width = symbol_width - .checked_add_signed(width_delta) - .ok_or(OverflowError::BitmapDimension)?; - ctx.total_width = ctx - .total_width - .checked_add(symbol_width) - .ok_or(OverflowError::BitmapDimension)?; + symbol_width = symbol_width.checked_add_signed(width_delta).ok_or(OverflowError::BitmapDimension)?; + ctx.total_width = ctx.total_width.checked_add(symbol_width).ok_or(OverflowError::BitmapDimension)?; // PdfCraft patch: see `MAX_DICTIONARY_PIXELS`. - ctx.pixels = ctx - .pixels - .saturating_add(u64::from(symbol_width) * u64::from(ctx.height_class_height)); + ctx.pixels = ctx.pixels.saturating_add(u64::from(symbol_width) * u64::from(ctx.height_class_height)); if ctx.pixels > MAX_DICTIONARY_PIXELS { bail!(OverflowError::BitmapLimit); } @@ -199,18 +172,12 @@ pub(crate) fn decode( let exported = export_symbols(&mut ctx)?; let retained_contexts = if ctx.header.flags.bitmap_context_retained { - Some(RetainedContexts { - generic_region: ctx.a_ctx.generic_region_contexts, - refinement_region: ctx.a_ctx.refinement_region_contexts, - }) + Some(RetainedContexts { generic_region: ctx.a_ctx.generic_region_contexts, refinement_region: ctx.a_ctx.refinement_region_contexts }) } else { None }; - Ok(SymbolDictionary { - exported_symbols: exported, - retained_contexts, - }) + Ok(SymbolDictionary { exported_symbols: exported, retained_contexts }) } #[derive(Debug, Clone)] @@ -239,19 +206,12 @@ impl SymbolDictionary { } /// Decode a symbol bitmap using refinement/aggregate coding (6.5.8.2). -fn decode_refinement_aggregation_bitmap( - ctx: &mut SymbolDecodeContext<'_>, - symbol_width: u32, -) -> Result { +fn decode_refinement_aggregation_bitmap(ctx: &mut SymbolDecodeContext<'_>, symbol_width: u32) -> Result { // 6.5.8.2.1 Number of symbol instances in the aggregation. let aggregation_instance_count = if ctx.header.flags.use_huffman { - ctx.h_ctx - .aggregation_instance_count_table - .decode(&mut ctx.h_ctx.reader)? + ctx.h_ctx.aggregation_instance_count_table.decode(&mut ctx.h_ctx.reader)? } else { - ctx.a_ctx - .aggregation_instance_count_decoder - .decode(&mut ctx.a_ctx.decoder) + ctx.a_ctx.aggregation_instance_count_decoder.decode(&mut ctx.a_ctx.decoder) } .ok_or(DecodeError::Symbol(SymbolError::UnexpectedOob))?; @@ -265,10 +225,7 @@ fn decode_refinement_aggregation_bitmap( } /// Decode a refinement bitmap symbol with a single aggregate (6.5.8.2). -fn decode_refinement_bitmap( - ctx: &mut SymbolDecodeContext<'_>, - symbol_width: u32, -) -> Result { +fn decode_refinement_bitmap(ctx: &mut SymbolDecodeContext<'_>, symbol_width: u32) -> Result { let use_huffman = ctx.header.flags.use_huffman; let mut symbol_code_length = 32 - (ctx.total_symbols() - 1).leading_zeros(); @@ -276,44 +233,23 @@ fn decode_refinement_bitmap( // See 6.5.8.2.3, the value should be at least 1 if we use huffman coding. symbol_code_length = symbol_code_length.max(1); - let symbol_id = ctx - .h_ctx - .reader - .read_bits(symbol_code_length as u8) - .ok_or(ParseError::UnexpectedEof)? as usize; + let symbol_id = ctx.h_ctx.reader.read_bits(symbol_code_length as u8).ok_or(ParseError::UnexpectedEof)? as usize; - let refinement_x_offset = ctx - .standard_tables - .table_o() - .decode(&mut ctx.h_ctx.reader)? - .ok_or(HuffmanError::UnexpectedOob)?; + let refinement_x_offset = ctx.standard_tables.table_o().decode(&mut ctx.h_ctx.reader)?.ok_or(HuffmanError::UnexpectedOob)?; - let refinement_y_offset = ctx - .standard_tables - .table_o() - .decode(&mut ctx.h_ctx.reader)? - .ok_or(HuffmanError::UnexpectedOob)?; + let refinement_y_offset = ctx.standard_tables.table_o().decode(&mut ctx.h_ctx.reader)?.ok_or(HuffmanError::UnexpectedOob)?; (symbol_id, refinement_x_offset, refinement_y_offset) } else { // Note that the contexts should be reused across multiple // bitmaps in the same symbol dictionary. - let contexts = ctx - .a_ctx - .text_region_contexts - .get_or_insert_with(|| TextRegionContexts::new(symbol_code_length)); + let contexts = ctx.a_ctx.text_region_contexts.get_or_insert_with(|| TextRegionContexts::new(symbol_code_length)); let symbol_id = contexts.iaid.decode(&mut ctx.a_ctx.decoder) as usize; - let refinement_x_offset = contexts - .iardx - .decode(&mut ctx.a_ctx.decoder) - .ok_or(SymbolError::UnexpectedOob)?; + let refinement_x_offset = contexts.iardx.decode(&mut ctx.a_ctx.decoder).ok_or(SymbolError::UnexpectedOob)?; - let refinement_y_offset = contexts - .iardy - .decode(&mut ctx.a_ctx.decoder) - .ok_or(SymbolError::UnexpectedOob)?; + let refinement_y_offset = contexts.iardy.decode(&mut ctx.a_ctx.decoder).ok_or(SymbolError::UnexpectedOob)?; (symbol_id, refinement_x_offset, refinement_y_offset) }; @@ -322,18 +258,10 @@ fn decode_refinement_bitmap( let mut region = Bitmap::new(symbol_width, ctx.height_class_height)?; if use_huffman { - let bitmap_size = ctx - .standard_tables - .table_a() - .decode(&mut ctx.h_ctx.reader)? - .ok_or(HuffmanError::UnexpectedOob)? as usize; + let bitmap_size = ctx.standard_tables.table_a().decode(&mut ctx.h_ctx.reader)?.ok_or(HuffmanError::UnexpectedOob)? as usize; ctx.h_ctx.reader.align(); - let bitmap_data = ctx - .h_ctx - .reader - .read_bytes(bitmap_size) - .ok_or(ParseError::UnexpectedEof)?; + let bitmap_data = ctx.h_ctx.reader.read_bytes(bitmap_size).ok_or(ParseError::UnexpectedEof)?; let mut bitmap_decoder = ArithmeticDecoder::new(bitmap_data); @@ -366,11 +294,7 @@ fn decode_refinement_bitmap( } /// Decode an aggregation bitmap with more than one aggregate (6.5.8.2). -fn decode_aggregation_bitmap( - ctx: &mut SymbolDecodeContext<'_>, - symbol_width: u32, - aggregation_instance_count: u32, -) -> Result { +fn decode_aggregation_bitmap(ctx: &mut SymbolDecodeContext<'_>, symbol_width: u32, aggregation_instance_count: u32) -> Result { let use_huffman = ctx.header.flags.use_huffman; // PdfCraft patch: see `bitmap::MAX_WORK`. What follows is sized by all the symbols, for each @@ -379,8 +303,7 @@ fn decode_aggregation_bitmap( *ctx.work_left = ctx.work_left.checked_sub(work).ok_or(OverflowError::DecodingWork)?; // Concatenate input and new symbols. - let mut all_symbols: Vec<&Bitmap> = - Vec::with_capacity(ctx.symbols.input.len() + ctx.symbols.new.len()); + let mut all_symbols: Vec<&Bitmap> = Vec::with_capacity(ctx.symbols.input.len() + ctx.symbols.new.len()); all_symbols.extend(ctx.symbols.input.iter().copied()); for sym in &ctx.symbols.new { all_symbols.push(sym); @@ -390,14 +313,7 @@ fn decode_aggregation_bitmap( let symbol_code_length = 32 - (ctx.total_symbols() - 1).leading_zeros(); - let symbol_id_table = if use_huffman { - Some(HuffmanTable::build_uniform( - ctx.total_symbols(), - symbol_code_length, - )?) - } else { - None - }; + let symbol_id_table = if use_huffman { Some(HuffmanTable::build_uniform(ctx.total_symbols(), symbol_code_length)?) } else { None }; let huffman_flags = if use_huffman { Some(TextRegionHuffmanFlags { @@ -444,16 +360,9 @@ fn decode_aggregation_bitmap( let decode_ctx = if use_huffman { DecodeContext::new_huffman(&mut ctx.h_ctx.reader, &header, &[], ctx.standard_tables)? } else { - let contexts = ctx - .a_ctx - .text_region_contexts - .get_or_insert_with(|| TextRegionContexts::new(symbol_code_length)); + let contexts = ctx.a_ctx.text_region_contexts.get_or_insert_with(|| TextRegionContexts::new(symbol_code_length)); - DecodeContext::new_arithmetic( - &mut ctx.a_ctx.decoder, - contexts, - &mut ctx.a_ctx.refinement_region_contexts, - ) + DecodeContext::new_arithmetic(&mut ctx.a_ctx.decoder, contexts, &mut ctx.a_ctx.refinement_region_contexts) }; let mut bitmap = Bitmap::new_with( @@ -474,10 +383,7 @@ struct Symbols<'a> { impl<'a> Symbols<'a> { fn new(input: &'a [&'a Bitmap], capacity: usize) -> Self { - Self { - input, - new: Vec::with_capacity(capacity), - } + Self { input, new: Vec::with_capacity(capacity) } } fn input_count(&self) -> u32 { @@ -485,11 +391,7 @@ impl<'a> Symbols<'a> { } fn get(&self, index: usize) -> Option<&Bitmap> { - if index < self.input.len() { - Some(self.input[index]) - } else { - self.new.get(index - self.input.len()) - } + if index < self.input.len() { Some(self.input[index]) } else { self.new.get(index - self.input.len()) } } } @@ -538,11 +440,7 @@ struct ArithmeticContext<'a> { } impl<'a> ArithmeticContext<'a> { - fn new( - data: &'a [u8], - header: &SymbolDictionaryHeader<'_>, - input_contexts: Option<&RetainedContexts>, - ) -> Result { + fn new(data: &'a [u8], header: &SymbolDictionaryHeader<'_>, input_contexts: Option<&RetainedContexts>) -> Result { let decoder = ArithmeticDecoder::new(data); let height_class_delta_decoder = IntegerDecoder::new(); @@ -550,20 +448,16 @@ impl<'a> ArithmeticContext<'a> { let export_run_length_decoder = IntegerDecoder::new(); let aggregation_instance_count_decoder = IntegerDecoder::new(); - let (generic_region_contexts, refinement_region_contexts) = - if header.flags.bitmap_context_used { - let ctx = input_contexts.ok_or(SymbolError::Invalid)?; - (ctx.generic_region.clone(), ctx.refinement_region.clone()) - } else { - let template = header.flags.template; - let num_contexts = 1 << template.context_bits(); - let refinement_template = header.flags.refinement_template; - let num_refinement_contexts = 1 << refinement_template.context_bits(); - ( - vec![ArithmeticDecoderContext::default(); num_contexts], - vec![ArithmeticDecoderContext::default(); num_refinement_contexts], - ) - }; + let (generic_region_contexts, refinement_region_contexts) = if header.flags.bitmap_context_used { + let ctx = input_contexts.ok_or(SymbolError::Invalid)?; + (ctx.generic_region.clone(), ctx.refinement_region.clone()) + } else { + let template = header.flags.template; + let num_contexts = 1 << template.context_bits(); + let refinement_template = header.flags.refinement_template; + let num_refinement_contexts = 1 << refinement_template.context_bits(); + (vec![ArithmeticDecoderContext::default(); num_contexts], vec![ArithmeticDecoderContext::default(); num_refinement_contexts]) + }; Ok(Self { decoder, @@ -652,11 +546,7 @@ impl<'a> HuffmanContext<'a> { /// Decode a height class collective bitmap (6.5.9). fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> Result<()> { - let bitmap_size = ctx - .h_ctx - .collective_bitmap_size_table - .decode(&mut ctx.h_ctx.reader)? - .ok_or(HuffmanError::UnexpectedOob)?; + let bitmap_size = ctx.h_ctx.collective_bitmap_size_table.decode(&mut ctx.h_ctx.reader)?.ok_or(HuffmanError::UnexpectedOob)?; let bitmap_size = u32::try_from(bitmap_size).map_err(|_| OverflowError::BitmapDimension)?; ctx.h_ctx.reader.align(); @@ -665,10 +555,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R // rows by the symbol, so decoding this would be rows for nothing: 65,535 a class, and a dictionary // can hold a thousand such classes. Its bytes still have to be stepped over. if ctx.symbols_decoded_count == ctx.height_class_first_symbol { - ctx.h_ctx - .reader - .read_bytes(bitmap_size as usize) - .ok_or(ParseError::UnexpectedEof)?; + ctx.h_ctx.reader.read_bytes(bitmap_size as usize).ok_or(ParseError::UnexpectedEof)?; return Ok(()); } @@ -680,11 +567,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height)?; for y in 0..ctx.height_class_height { for byte_x in 0..row_bytes { - let byte = ctx - .h_ctx - .reader - .read_byte() - .ok_or(ParseError::UnexpectedEof)?; + let byte = ctx.h_ctx.reader.read_byte().ok_or(ParseError::UnexpectedEof)?; for bit in 0..8 { let x = byte_x * 8 + bit; if x < ctx.total_width { @@ -697,11 +580,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R bitmap } else { // Otherwise, we need to use MMR decoding. - let bitmap_data = ctx - .h_ctx - .reader - .read_bytes(bitmap_size as usize) - .ok_or(ParseError::UnexpectedEof)?; + let bitmap_data = ctx.h_ctx.reader.read_bytes(bitmap_size as usize).ok_or(ParseError::UnexpectedEof)?; let mut bitmap = Bitmap::new(ctx.total_width, ctx.height_class_height)?; decode_bitmap_mmr(&mut bitmap, bitmap_data)?; @@ -741,9 +620,7 @@ fn decode_height_class_collective_bitmap(ctx: &mut SymbolDecodeContext<'_>) -> R } ctx.symbols.new.push(symbol); - x_offset = x_offset - .checked_add(symbol_width) - .ok_or(OverflowError::Index)?; + x_offset = x_offset.checked_add(symbol_width).ok_or(OverflowError::Index)?; } Ok(()) @@ -755,13 +632,9 @@ fn export_symbols(ctx: &mut SymbolDecodeContext<'_>) -> Result> { let mut read_run_length = || -> Result { let value = if ctx.header.flags.use_huffman { - ctx.h_ctx - .export_run_length_table - .decode(&mut ctx.h_ctx.reader)? + ctx.h_ctx.export_run_length_table.decode(&mut ctx.h_ctx.reader)? } else { - ctx.a_ctx - .export_run_length_decoder - .decode(&mut ctx.a_ctx.decoder) + ctx.a_ctx.export_run_length_decoder.decode(&mut ctx.a_ctx.decoder) } .ok_or(HuffmanError::UnexpectedOob)?; @@ -790,10 +663,7 @@ fn export_symbols(ctx: &mut SymbolDecodeContext<'_>) -> Result> { if should_export { for symbol_idx in index..end_index { - let symbol = ctx - .symbols - .get(symbol_idx as usize) - .ok_or(SymbolError::OutOfRange)?; + let symbol = ctx.symbols.get(symbol_idx as usize).ok_or(SymbolError::OutOfRange)?; // PdfCraft patch: see `room`. exported_words = exported_words.saturating_add(symbol.words() as u64); if exported_words > ctx.room { @@ -870,17 +740,9 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result bail!(HuffmanError::InvalidSelection), }; - let collective_bitmap_size_table = if flags_word & 0x0040 != 0 { - HuffmanTableSelection::UserSupplied - } else { - HuffmanTableSelection::TableB1 - }; + let collective_bitmap_size_table = if flags_word & 0x0040 != 0 { HuffmanTableSelection::UserSupplied } else { HuffmanTableSelection::TableB1 }; - let aggregate_instance_table = if flags_word & 0x0080 != 0 { - HuffmanTableSelection::UserSupplied - } else { - HuffmanTableSelection::TableB1 - }; + let aggregate_instance_table = if flags_word & 0x0080 != 0 { HuffmanTableSelection::UserSupplied } else { HuffmanTableSelection::TableB1 }; let bitmap_context_used = flags_word & 0x0100 != 0; let bitmap_context_retained = flags_word & 0x0200 != 0; @@ -907,12 +769,8 @@ pub(crate) fn parse<'a>(reader: &mut Reader<'a>) -> Result(reader: &mut Reader<'a>) -> Result Result<()> { if header.flags.use_huffman { let mut reader = Reader::new(header.data); - let ctx = - DecodeContext::new_huffman(&mut reader, header, referred_tables, standard_tables)?; + let ctx = DecodeContext::new_huffman(&mut reader, header, referred_tables, standard_tables)?; decode_with(ctx, symbols, header, bitmap, work_left)?; } else { let mut decoder = ArithmeticDecoder::new(header.data); @@ -74,9 +61,7 @@ pub(crate) fn decode_into( let num_gr_contexts = 1 << header.flags.refinement_template.context_bits(); scratch.contexts.clear(); - scratch - .contexts - .resize(num_gr_contexts, ArithmeticDecoderContext::default()); + scratch.contexts.resize(num_gr_contexts, ArithmeticDecoderContext::default()); let ctx = DecodeContext::new_arithmetic(&mut decoder, &mut contexts, &mut scratch.contexts); decode_with(ctx, symbols, header, bitmap, work_left)?; @@ -102,18 +87,13 @@ pub(crate) fn decode_with( bail!(SymbolError::TooManyInstances); } - let mut strip_t = ctx - .read_strip_delta_t(strip_size)? - .checked_neg() - .ok_or(OverflowError::PlacementCoordinate)?; + let mut strip_t = ctx.read_strip_delta_t(strip_size)?.checked_neg().ok_or(OverflowError::PlacementCoordinate)?; let mut first_s: i32 = 0; let mut instance_count = 0; while instance_count < header.num_instances { let delta_t = ctx.read_strip_delta_t(strip_size)?; - strip_t = strip_t - .checked_add(delta_t) - .ok_or(OverflowError::PlacementCoordinate)?; + strip_t = strip_t.checked_add(delta_t).ok_or(OverflowError::PlacementCoordinate)?; let mut first_symbol_in_strip = true; let mut current_s = 0; @@ -126,9 +106,7 @@ pub(crate) fn decode_with( if first_symbol_in_strip { let delta_first_s = ctx.read_first_s()?; - first_s = first_s - .checked_add(delta_first_s) - .ok_or(OverflowError::PlacementCoordinate)?; + first_s = first_s.checked_add(delta_first_s).ok_or(OverflowError::PlacementCoordinate)?; current_s = first_s; first_symbol_in_strip = false; } else { @@ -144,14 +122,11 @@ pub(crate) fn decode_with( } let current_t = ctx.read_symbol_t(strip_size, header.flags.log_strip_size)?; - let symbol_t = strip_t - .checked_add(current_t) - .ok_or(OverflowError::PlacementCoordinate)?; + let symbol_t = strip_t.checked_add(current_t).ok_or(OverflowError::PlacementCoordinate)?; let symbol_id = ctx.read_symbol_id()?; - let symbol_bitmap = - decode_symbol_instance_bitmap(&mut ctx, symbols, header, symbol_id, work_left)?; + let symbol_bitmap = decode_symbol_instance_bitmap(&mut ctx, symbols, header, symbol_id, work_left)?; let symbol_bitmap_ref: &Bitmap = match &symbol_bitmap { SymbolBitmap::Reference(idx) => symbols.get(*idx).ok_or(SymbolError::OutOfRange)?, @@ -166,19 +141,13 @@ pub(crate) fn decode_with( *work_left = work_left.checked_sub(work).ok_or(OverflowError::DecodingWork)?; if !header.flags.transposed - && (header.flags.reference_corner == ReferenceCorner::TopRight - || header.flags.reference_corner == ReferenceCorner::BottomRight) + && (header.flags.reference_corner == ReferenceCorner::TopRight || header.flags.reference_corner == ReferenceCorner::BottomRight) { - current_s = current_s - .checked_add(symbol_width - 1) - .ok_or(OverflowError::PlacementCoordinate)?; + current_s = current_s.checked_add(symbol_width - 1).ok_or(OverflowError::PlacementCoordinate)?; } else if header.flags.transposed - && (header.flags.reference_corner == ReferenceCorner::BottomLeft - || header.flags.reference_corner == ReferenceCorner::BottomRight) + && (header.flags.reference_corner == ReferenceCorner::BottomLeft || header.flags.reference_corner == ReferenceCorner::BottomRight) { - current_s = current_s - .checked_add(symbol_height - 1) - .ok_or(OverflowError::PlacementCoordinate)?; + current_s = current_s.checked_add(symbol_height - 1).ok_or(OverflowError::PlacementCoordinate)?; } let symbol_s = current_s; @@ -191,37 +160,27 @@ pub(crate) fn decode_with( ReferenceCorner::TopLeft => (symbol_s, symbol_t), ReferenceCorner::TopRight => (back(symbol_s, symbol_width), symbol_t), ReferenceCorner::BottomLeft => (symbol_s, back(symbol_t, symbol_height)), - ReferenceCorner::BottomRight => { - (back(symbol_s, symbol_width), back(symbol_t, symbol_height)) - } + ReferenceCorner::BottomRight => (back(symbol_s, symbol_width), back(symbol_t, symbol_height)), } } else { match header.flags.reference_corner { ReferenceCorner::TopLeft => (symbol_t, symbol_s), ReferenceCorner::TopRight => (back(symbol_t, symbol_width), symbol_s), ReferenceCorner::BottomLeft => (symbol_t, back(symbol_s, symbol_height)), - ReferenceCorner::BottomRight => { - (back(symbol_t, symbol_width), back(symbol_s, symbol_height)) - } + ReferenceCorner::BottomRight => (back(symbol_t, symbol_width), back(symbol_s, symbol_height)), } }; region.combine(symbol_bitmap_ref, x, y, header.flags.combination_operator); if !header.flags.transposed - && (header.flags.reference_corner == ReferenceCorner::TopLeft - || header.flags.reference_corner == ReferenceCorner::BottomLeft) + && (header.flags.reference_corner == ReferenceCorner::TopLeft || header.flags.reference_corner == ReferenceCorner::BottomLeft) { - current_s = current_s - .checked_add(symbol_width - 1) - .ok_or(OverflowError::PlacementCoordinate)?; + current_s = current_s.checked_add(symbol_width - 1).ok_or(OverflowError::PlacementCoordinate)?; } else if header.flags.transposed - && (header.flags.reference_corner == ReferenceCorner::TopLeft - || header.flags.reference_corner == ReferenceCorner::TopRight) + && (header.flags.reference_corner == ReferenceCorner::TopLeft || header.flags.reference_corner == ReferenceCorner::TopRight) { - current_s = current_s - .checked_add(symbol_height - 1) - .ok_or(OverflowError::PlacementCoordinate)?; + current_s = current_s.checked_add(symbol_height - 1).ok_or(OverflowError::PlacementCoordinate)?; } instance_count += 1; @@ -274,16 +233,8 @@ impl TextRegionContexts { } pub(crate) enum DecodeContext<'a, 'b> { - Huffman { - reader: &'a mut Reader<'b>, - tables: TextRegionHuffmanTables<'a>, - symbol_codes: &'a HuffmanTable, - }, - Arithmetic { - decoder: &'a mut ArithmeticDecoder<'b>, - contexts: &'a mut TextRegionContexts, - gr_contexts: &'a mut [ArithmeticDecoderContext], - }, + Huffman { reader: &'a mut Reader<'b>, tables: TextRegionHuffmanTables<'a>, symbol_codes: &'a HuffmanTable }, + Arithmetic { decoder: &'a mut ArithmeticDecoder<'b>, contexts: &'a mut TextRegionContexts, gr_contexts: &'a mut [ArithmeticDecoderContext] }, } impl<'a, 'b> DecodeContext<'a, 'b> { @@ -293,21 +244,11 @@ impl<'a, 'b> DecodeContext<'a, 'b> { referred_tables: &'a [HuffmanTable], standard_tables: &'a StandardHuffmanTables, ) -> Result { - let huffman_flags = header - .huffman_flags - .as_ref() - .ok_or(HuffmanError::InvalidSelection)?; + let huffman_flags = header.huffman_flags.as_ref().ok_or(HuffmanError::InvalidSelection)?; let tables = select_huffman_tables(huffman_flags, referred_tables, standard_tables)?; - let symbol_codes = header - .symbol_id_table - .as_ref() - .ok_or(HuffmanError::MissingTables)?; + let symbol_codes = header.symbol_id_table.as_ref().ok_or(HuffmanError::MissingTables)?; - Ok(DecodeContext::Huffman { - reader, - tables, - symbol_codes, - }) + Ok(DecodeContext::Huffman { reader, tables, symbol_codes }) } pub(crate) fn new_arithmetic( @@ -315,31 +256,18 @@ impl<'a, 'b> DecodeContext<'a, 'b> { contexts: &'a mut TextRegionContexts, gr_contexts: &'a mut [ArithmeticDecoderContext], ) -> Self { - DecodeContext::Arithmetic { - decoder, - contexts, - gr_contexts, - } + DecodeContext::Arithmetic { decoder, contexts, gr_contexts } } fn read_strip_delta_t(&mut self, strip_size: u32) -> Result { match self { DecodeContext::Huffman { reader, tables, .. } => { let value = tables.delta_t.decode_no_oob(reader)?; - value - .checked_mul(strip_size as i32) - .ok_or(SymbolError::InvalidStripDelta.into()) + value.checked_mul(strip_size as i32).ok_or(SymbolError::InvalidStripDelta.into()) } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => { - let value = contexts - .iadt - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob)?; - value - .checked_mul(strip_size as i32) - .ok_or(SymbolError::InvalidStripDelta.into()) + DecodeContext::Arithmetic { decoder, contexts, .. } => { + let value = contexts.iadt.decode(decoder).ok_or(SymbolError::UnexpectedOob)?; + value.checked_mul(strip_size as i32).ok_or(SymbolError::InvalidStripDelta.into()) } } } @@ -348,12 +276,7 @@ impl<'a, 'b> DecodeContext<'a, 'b> { fn read_first_s(&mut self) -> Result { match self { DecodeContext::Huffman { reader, tables, .. } => tables.first_s.decode_no_oob(reader), - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iafs - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iafs.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } @@ -361,9 +284,7 @@ impl<'a, 'b> DecodeContext<'a, 'b> { fn read_delta_s(&mut self) -> Result> { match self { DecodeContext::Huffman { reader, tables, .. } => tables.delta_s.decode(reader), - DecodeContext::Arithmetic { - decoder, contexts, .. - } => Ok(contexts.iads.decode(decoder)), + DecodeContext::Arithmetic { decoder, contexts, .. } => Ok(contexts.iads.decode(decoder)), } } @@ -374,104 +295,55 @@ impl<'a, 'b> DecodeContext<'a, 'b> { } match self { - DecodeContext::Huffman { reader, .. } => reader - .read_bits(log_strip_size) - .ok_or(HuffmanError::InvalidCode.into()) - .map(|v| v as i32), - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iait - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Huffman { reader, .. } => reader.read_bits(log_strip_size).ok_or(HuffmanError::InvalidCode.into()).map(|v| v as i32), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iait.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } /// Decode symbol instance symbol ID (6.4.10). fn read_symbol_id(&mut self) -> Result { match self { - DecodeContext::Huffman { - reader, - symbol_codes, - .. - } => symbol_codes.decode_no_oob(reader).map(|v| v as usize), - DecodeContext::Arithmetic { - decoder, contexts, .. - } => Ok(contexts.iaid.decode(decoder) as usize), + DecodeContext::Huffman { reader, symbol_codes, .. } => symbol_codes.decode_no_oob(reader).map(|v| v as usize), + DecodeContext::Arithmetic { decoder, contexts, .. } => Ok(contexts.iaid.decode(decoder) as usize), } } fn read_refinement_flag(&mut self) -> Result { match self { - DecodeContext::Huffman { reader, .. } => { - reader.read_bit().ok_or(ParseError::UnexpectedEof.into()) - } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => Ok(contexts - .iari - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob)? as u8), + DecodeContext::Huffman { reader, .. } => reader.read_bit().ok_or(ParseError::UnexpectedEof.into()), + DecodeContext::Arithmetic { decoder, contexts, .. } => Ok(contexts.iari.decode(decoder).ok_or(SymbolError::UnexpectedOob)? as u8), } } /// Decode symbol instance refinement delta width (6.4.11.1). fn read_refinement_delta_width(&mut self) -> Result { match self { - DecodeContext::Huffman { reader, tables, .. } => { - tables.refinement_width.decode_no_oob(reader) - } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iardw - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Huffman { reader, tables, .. } => tables.refinement_width.decode_no_oob(reader), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iardw.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } /// Decode symbol instance refinement delta height (6.4.11.2). fn read_refinement_delta_height(&mut self) -> Result { match self { - DecodeContext::Huffman { reader, tables, .. } => { - tables.refinement_height.decode_no_oob(reader) - } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iardh - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Huffman { reader, tables, .. } => tables.refinement_height.decode_no_oob(reader), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iardh.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } /// Decode symbol instance refinement x offset (6.4.11.3). fn read_refinement_x_offset(&mut self) -> Result { match self { - DecodeContext::Huffman { reader, tables, .. } => { - tables.refinement_x.decode_no_oob(reader) - } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iardx - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Huffman { reader, tables, .. } => tables.refinement_x.decode_no_oob(reader), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iardx.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } /// Decode symbol instance refinement y offset (6.4.11.4). fn read_refinement_y_offset(&mut self) -> Result { match self { - DecodeContext::Huffman { reader, tables, .. } => { - tables.refinement_y.decode_no_oob(reader) - } - DecodeContext::Arithmetic { - decoder, contexts, .. - } => contexts - .iardy - .decode(decoder) - .ok_or(SymbolError::UnexpectedOob.into()), + DecodeContext::Huffman { reader, tables, .. } => tables.refinement_y.decode_no_oob(reader), + DecodeContext::Arithmetic { decoder, contexts, .. } => contexts.iardy.decode(decoder).ok_or(SymbolError::UnexpectedOob.into()), } } @@ -490,9 +362,7 @@ impl<'a, 'b> DecodeContext<'a, 'b> { let refinement_data_size = tables.refinement_size.decode_no_oob(reader)? as u32; reader.align(); - let refinement_data = reader - .read_bytes(refinement_data_size as usize) - .ok_or(ParseError::UnexpectedEof)?; + let refinement_data = reader.read_bytes(refinement_data_size as usize).ok_or(ParseError::UnexpectedEof)?; let mut decoder = ArithmeticDecoder::new(refinement_data); let num_context_bits = refinement_template.context_bits(); @@ -510,11 +380,7 @@ impl<'a, 'b> DecodeContext<'a, 'b> { false, ) } - DecodeContext::Arithmetic { - decoder, - gr_contexts, - .. - } => generic_refinement::decode_bitmap( + DecodeContext::Arithmetic { decoder, gr_contexts, .. } => generic_refinement::decode_bitmap( decoder, gr_contexts, refined, @@ -558,22 +424,11 @@ fn decode_symbol_instance_bitmap( let rdx = ctx.read_refinement_x_offset()?; let rdy = ctx.read_refinement_y_offset()?; - let refined_width = (reference_bitmap.width as i32) - .checked_add(rdw) - .and_then(|v| u32::try_from(v).ok()) - .ok_or(OverflowError::BitmapDimension)?; - let refined_height = (reference_bitmap.height as i32) - .checked_add(rdh) - .and_then(|v| u32::try_from(v).ok()) - .ok_or(OverflowError::BitmapDimension)?; - let reference_x_offset = rdw - .div_euclid(2) - .checked_add(rdx) - .ok_or(OverflowError::ReferenceOffset)?; - let reference_y_offset = rdh - .div_euclid(2) - .checked_add(rdy) - .ok_or(OverflowError::ReferenceOffset)?; + let refined_width = (reference_bitmap.width as i32).checked_add(rdw).and_then(|v| u32::try_from(v).ok()).ok_or(OverflowError::BitmapDimension)?; + let refined_height = + (reference_bitmap.height as i32).checked_add(rdh).and_then(|v| u32::try_from(v).ok()).ok_or(OverflowError::BitmapDimension)?; + let reference_x_offset = rdw.div_euclid(2).checked_add(rdx).ok_or(OverflowError::ReferenceOffset)?; + let reference_y_offset = rdh.div_euclid(2).checked_add(rdy).ok_or(OverflowError::ReferenceOffset)?; // PdfCraft patch: see `bitmap::MAX_WORK`. Before it is decoded: charged after, one instance // could still be 2^28 pixels past what was left. With the four integers that gave its size. @@ -603,9 +458,7 @@ fn select_huffman_tables<'a>( let mut custom_table_idx = 0; let mut get_custom = || -> Result<&'a HuffmanTable> { - let table = custom_tables - .get(custom_table_idx) - .ok_or(HuffmanError::MissingTables)?; + let table = custom_tables.get(custom_table_idx).ok_or(HuffmanError::MissingTables)?; custom_table_idx += 1; Ok(table) }; @@ -675,23 +528,11 @@ fn select_huffman_tables<'a>( _ => bail!(HuffmanError::InvalidSelection), }; - Ok(TextRegionHuffmanTables { - first_s, - delta_s, - delta_t, - refinement_width, - refinement_height, - refinement_y, - refinement_x, - refinement_size, - }) + Ok(TextRegionHuffmanTables { first_s, delta_s, delta_t, refinement_width, refinement_height, refinement_y, refinement_x, refinement_size }) } /// Decode the symbol ID Huffman table (7.4.3.1.7). -fn decode_symbol_id_huffman_table( - reader: &mut Reader<'_>, - num_symbols: u32, -) -> Result { +fn decode_symbol_id_huffman_table(reader: &mut Reader<'_>, num_symbols: u32) -> Result { let mut runcode_lines: Vec = Vec::with_capacity(35); for runcode_idx in 0..35 { let prefix_length = reader.read_bits(4).ok_or(HuffmanError::InvalidCode)? as u8; @@ -712,9 +553,7 @@ fn decode_symbol_id_huffman_table( // Copy previous 3-6 times. let extra_bits = reader.read_bits(2).ok_or(HuffmanError::InvalidCode)? as usize; let repeat = extra_bits + 3; - let previous_length = *symbol_code_lengths - .last() - .ok_or(HuffmanError::InvalidCode)?; + let previous_length = *symbol_code_lengths.last().ok_or(HuffmanError::InvalidCode)?; symbol_code_lengths.extend(iter::repeat_n(previous_length, repeat)); } 33 => { @@ -739,11 +578,8 @@ fn decode_symbol_id_huffman_table( reader.align(); - let symbol_lines: Vec = symbol_code_lengths - .iter() - .enumerate() - .map(|(symbol_idx, &prefix_length)| TableLine::new(symbol_idx as i32, prefix_length, 0)) - .collect(); + let symbol_lines: Vec = + symbol_code_lengths.iter().enumerate().map(|(symbol_idx, &prefix_length)| TableLine::new(symbol_idx as i32, prefix_length, 0)).collect(); HuffmanTable::build(&symbol_lines) } @@ -837,11 +673,7 @@ fn parse_text_region_flags(reader: &mut Reader<'_>) -> Result { let default_pixel = flags_word & 0x0200 != 0; let delta_s_offset_raw = ((flags_word >> 10) & 0x1F) as u8; - let delta_s_offset = if delta_s_offset_raw & 0x10 != 0 { - (delta_s_offset_raw | 0xE0) as i8 - } else { - delta_s_offset_raw as i8 - }; + let delta_s_offset = if delta_s_offset_raw & 0x10 != 0 { (delta_s_offset_raw | 0xE0) as i8 } else { delta_s_offset_raw as i8 }; let refinement_template = RefinementTemplate::from_byte((flags_word >> 15) as u8); @@ -886,36 +718,19 @@ fn parse_text_region_huffman_flags(reader: &mut Reader<'_>) -> Result(reader: &mut Reader<'a>, num_symbols: u32) -> Result> { let region_info = parse_region_segment_info(reader)?; let flags = parse_text_region_flags(reader)?; - let huffman_flags = if flags.use_huffman { - Some(parse_text_region_huffman_flags(reader)?) - } else { - None - }; + let huffman_flags = if flags.use_huffman { Some(parse_text_region_huffman_flags(reader)?) } else { None }; - let refinement_at_pixels = - if flags.use_refinement && flags.refinement_template == RefinementTemplate::Template0 { - parse_refinement_at_pixels(reader)? - } else { - Vec::new() - }; + let refinement_at_pixels = if flags.use_refinement && flags.refinement_template == RefinementTemplate::Template0 { + parse_refinement_at_pixels(reader)? + } else { + Vec::new() + }; let num_instances = reader.read_u32().ok_or(ParseError::UnexpectedEof)?; - let symbol_id_table = if flags.use_huffman { - Some(decode_symbol_id_huffman_table(reader, num_symbols)?) - } else { - None - }; + let symbol_id_table = if flags.use_huffman { Some(decode_symbol_id_huffman_table(reader, num_symbols)?) } else { None }; let data = reader.tail().ok_or(ParseError::UnexpectedEof)?; - Ok(TextRegionHeader { - region_info, - flags, - huffman_flags, - refinement_at_pixels, - num_instances, - symbol_id_table, - data, - }) + Ok(TextRegionHeader { region_info, flags, huffman_flags, refinement_at_pixels, num_instances, symbol_id_table, data }) } diff --git a/vendor/hayro-jbig2/src/file.rs b/vendor/hayro-jbig2/src/file.rs index c5b59b27c..e8210cdcb 100644 --- a/vendor/hayro-jbig2/src/file.rs +++ b/vendor/hayro-jbig2/src/file.rs @@ -7,9 +7,7 @@ use alloc::vec::Vec; use crate::error::{FormatError, OverflowError, ParseError, Result, bail}; use crate::reader::Reader; -use crate::segment::{ - Segment, SegmentType, parse_segment, parse_segment_data, parse_segment_header, -}; +use crate::segment::{Segment, SegmentType, parse_segment, parse_segment_data, parse_segment_header}; /// PdfCraft patch: the most segments a stream, with its globals, may have. They are all parsed and /// sorted before the first is decoded, at about 64 bytes for 11 of input, so behind nested Flate a @@ -112,10 +110,7 @@ pub(crate) fn parse_file(data: &[u8]) -> Result> { // are in sorted order, but just to be safe. segments.sort_by_key(|seg| seg.header.segment_number); - Ok(File { - _header: header, - segments, - }) + Ok(File { _header: header, segments }) } fn parse_file_header(reader: &mut Reader<'_>) -> Result { @@ -131,11 +126,7 @@ fn parse_file_header(reader: &mut Reader<'_>) -> Result { // "Bit 0: File organization type. If this bit is 0, the file uses the // random-access organization. If this bit is 1, the file uses the // sequential organization." (D.4.2) - let organization = if flags & 0x01 != 0 { - FileOrganization::Sequential - } else { - FileOrganization::RandomAccess - }; + let organization = if flags & 0x01 != 0 { FileOrganization::Sequential } else { FileOrganization::RandomAccess }; // "Bit 1: Unknown number of pages. If this bit is 0, then the number of // pages contained in the file is known. If this bit is 1, then the number @@ -159,11 +150,7 @@ fn parse_file_header(reader: &mut Reader<'_>) -> Result { // D.4.3: Number of pages // "This is a 4-byte field, and is not present if the 'unknown number of // pages' bit was 1." (D.4.3) - let number_of_pages = if unknown_page_count { - None - } else { - Some(reader.read_u32().ok_or(ParseError::UnexpectedEof)?) - }; + let number_of_pages = if unknown_page_count { None } else { Some(reader.read_u32().ok_or(ParseError::UnexpectedEof)?) }; Ok(FileHeader { organization, @@ -173,10 +160,7 @@ fn parse_file_header(reader: &mut Reader<'_>) -> Result { }) } -fn parse_segments<'a>( - reader: &mut Reader<'a>, - organization: FileOrganization, -) -> Result>> { +fn parse_segments<'a>(reader: &mut Reader<'a>, organization: FileOrganization) -> Result>> { let mut segments = Vec::new(); match organization { @@ -196,11 +180,7 @@ fn parse_segments<'a>( /// "In this organization, the file structure looks like Figure D.1. A file header /// is followed by a sequence of segments. The two parts of each segment are stored /// together: first the segment header then the segment data." (D.1) -pub(crate) fn parse_segments_sequential<'a>( - reader: &mut Reader<'a>, - segments: &mut Vec>, - count: &mut SegmentCount, -) -> Result<()> { +pub(crate) fn parse_segments_sequential<'a>(reader: &mut Reader<'a>, segments: &mut Vec>, count: &mut SegmentCount) -> Result<()> { loop { if reader.at_end() { break; @@ -228,11 +208,7 @@ pub(crate) fn parse_segments_sequential<'a>( /// is followed by a sequence of segments headers; the last segment header is /// followed by the data for the first segment, then the data for the second /// segment, and so on." (D.2) -pub(crate) fn parse_segments_random_access<'a>( - reader: &mut Reader<'a>, - segments: &mut Vec>, - count: &mut SegmentCount, -) -> Result<()> { +pub(crate) fn parse_segments_random_access<'a>(reader: &mut Reader<'a>, segments: &mut Vec>, count: &mut SegmentCount) -> Result<()> { let mut headers = Vec::new(); loop { diff --git a/vendor/hayro-jbig2/src/gray_scale.rs b/vendor/hayro-jbig2/src/gray_scale.rs index 1cd5016f0..3e7e67ef7 100644 --- a/vendor/hayro-jbig2/src/gray_scale.rs +++ b/vendor/hayro-jbig2/src/gray_scale.rs @@ -33,17 +33,9 @@ pub(crate) struct GrayScaleParams<'a> { /// /// Returns `GSVALS`: the decoded gray-scale image array, GSW × GSH pixels. #[inline(always)] -pub(crate) fn decode_gray_scale_image( - data: &[u8], - params: &GrayScaleParams<'_>, - ctx: &mut ScratchBuffers, -) -> Result> { +pub(crate) fn decode_gray_scale_image(data: &[u8], params: &GrayScaleParams<'_>, ctx: &mut ScratchBuffers) -> Result> { // Table C.1: "GSMMR specifies whether MMR is used." - if params.use_mmr { - decode_mmr(data, params) - } else { - decode_arithmetic(data, params, ctx) - } + if params.use_mmr { decode_mmr(data, params) } else { decode_arithmetic(data, params, ctx) } } /// The gray-scale image decoding procedure using MMR (Annex C, C.5). @@ -70,11 +62,7 @@ fn decode_mmr(data: &[u8], params: &GrayScaleParams<'_>) -> Result> { /// The gray-scale image decoding procedure using arithmetic coding (Annex C, C.5). /// /// Table C.4: "GBTEMPLATE = GSTEMPLATE, TPGDON = 0, USESKIP = GSUSESKIP, SKIP = GSKIP" -fn decode_arithmetic( - data: &[u8], - params: &GrayScaleParams<'_>, - ctx: &mut ScratchBuffers, -) -> Result> { +fn decode_arithmetic(data: &[u8], params: &GrayScaleParams<'_>, ctx: &mut ScratchBuffers) -> Result> { // `GSW` - The width of the gray-scale image. let width = params.width; // `GSH` - The height of the gray-scale image. @@ -123,10 +111,7 @@ fn decode_arithmetic( let mut decoder = ArithmeticDecoder::new(data); ctx.contexts.clear(); - ctx.contexts.resize( - 1 << template.context_bits(), - ArithmeticDecoderContext::default(), - ); + ctx.contexts.resize(1 << template.context_bits(), ArithmeticDecoderContext::default()); macro_rules! gs_decode_loop { ($gather:expr) => { @@ -177,13 +162,7 @@ fn decode_arithmetic( /// /// The closure `decode_next` is called for each bitplane, receiving the bitplane /// index (`GSBPP`-1 down to 0) and a zeroed bitmap to decode into. -fn decode_bitplanes( - width: u32, - height: u32, - stride: u32, - bits_per_pixel: u32, - mut decode_next: F, -) -> Result> +fn decode_bitplanes(width: u32, height: u32, stride: u32, bits_per_pixel: u32, mut decode_next: F) -> Result> where F: FnMut(u32, &mut Bitmap) -> Result<()>, { @@ -234,15 +213,7 @@ fn xor_planes(simd: S, plane: &mut [u32], prev: &[u32]) { } #[inline(always)] -fn extract_bits( - simd: S, - data: &[u32], - values: &mut [u32], - width: u32, - height: u32, - stride: u32, - j: u32, -) { +fn extract_bits(simd: S, data: &[u32], values: &mut [u32], width: u32, height: u32, stride: u32, j: u32) { /// Bit masks for extracting individual bits from a packed u32 word (MSB-first). /// `BIT_MASKS[i] = 1 << (31 - i)`. const BIT_MASKS: [u32; 32] = { @@ -269,8 +240,7 @@ fn extract_bits( let bit_offset = x % 32; let splatted = u32x8::splat(simd, word); - let masks = - u32x8::from_slice(simd, &BIT_MASKS[bit_offset..bit_offset + simd::SIMD_WIDTH]); + let masks = u32x8::from_slice(simd, &BIT_MASKS[bit_offset..bit_offset + simd::SIMD_WIDTH]); let extracted = splatted & masks; let nonzero = extracted.simd_gt(zero); let contribution = nonzero.select(bit_value, zero); @@ -301,22 +271,11 @@ mod pdfcraft_limit_tests { #[test] fn a_gray_scale_image_past_its_bounds_is_refused_by_a_limit() { let decode = |width, height| { - let params = GrayScaleParams { - use_mmr: false, - bits_per_pixel: 1, - width, - height, - template: Template::Template0, - skip_mask: None, - }; + let params = GrayScaleParams { use_mmr: false, bits_per_pixel: 1, width, height, template: Template::Template0, skip_mask: None }; decode_gray_scale_image(&[], ¶ms, &mut ScratchBuffers::default()).map(|_| ()) }; let limit = Err(DecodeError::Overflow(OverflowError::BitmapLimit)); assert_eq!(decode(MAX_DIMENSION + 1, 1), limit, "a side"); - assert_eq!( - decode(1 << 13, (1 << 12) + 1), - limit, - "the cells, each side within its bound" - ); + assert_eq!(decode(1 << 13, (1 << 12) + 1), limit, "the cells, each side within its bound"); } } diff --git a/vendor/hayro-jbig2/src/huffman_table.rs b/vendor/hayro-jbig2/src/huffman_table.rs index 1a20da528..4a5db3028 100644 --- a/vendor/hayro-jbig2/src/huffman_table.rs +++ b/vendor/hayro-jbig2/src/huffman_table.rs @@ -100,10 +100,8 @@ impl HuffmanTable { // a) "Set: FIRSTCODE[CURLEN] = (FIRSTCODE[CURLEN − 1] + LENCOUNT[CURLEN − 1]) × 2 // CURCODE = FIRSTCODE[CURLEN] // CURTEMP = 0" - first_code_per_length[current_length] = (first_code_per_length[current_length - 1] - + length_counts[current_length - 1]) - .checked_mul(2) - .ok_or(HuffmanError::InvalidCode)?; + first_code_per_length[current_length] = + (first_code_per_length[current_length - 1] + length_counts[current_length - 1]).checked_mul(2).ok_or(HuffmanError::InvalidCode)?; // `CURCODE` - Current code value being assigned. let mut current_code = first_code_per_length[current_length]; @@ -115,9 +113,7 @@ impl HuffmanTable { // CURCODE = CURCODE + 1" if lines[line_index].prefix_length as usize == current_length { assigned_codes[line_index] = current_code; - current_code = current_code - .checked_add(1) - .ok_or(HuffmanError::InvalidCode)?; + current_code = current_code.checked_add(1).ok_or(HuffmanError::InvalidCode)?; } // ii) "Set CURTEMP = CURTEMP + 1" (implicit in for loop) } @@ -154,9 +150,7 @@ impl HuffmanTable { /// 0 to SDNUMINSYMS + NSYMSDECODED – 1, set SBSYMCODES[i] to the binary /// representation of i using a SBSYMCODELEN-bit string." pub(crate) fn build_uniform(num_symbols: u32, code_length: u32) -> Result { - let lines: Vec = (0..num_symbols) - .map(|i| TableLine::new(i as i32, code_length as u8, 0)) - .collect(); + let lines: Vec = (0..num_symbols).map(|i| TableLine::new(i as i32, code_length as u8, 0)).collect(); Self::build(&lines) } @@ -173,8 +167,7 @@ impl HuffmanTable { ) -> Result<()> { if prefix_length == 0 { // We've consumed all bits, this should be a leaf. - nodes[node_index as usize] = - HuffmanNode::new_leaf(range_low, range_length, is_lower, is_out_of_band); + nodes[node_index as usize] = HuffmanNode::new_leaf(range_low, range_length, is_lower, is_out_of_band); return Ok(()); } @@ -192,16 +185,7 @@ impl HuffmanTable { } }; - Self::insert_code( - nodes, - child_index.get(), - remaining_code, - prefix_length - 1, - range_low, - range_length, - is_lower, - is_out_of_band, - ) + Self::insert_code(nodes, child_index.get(), remaining_code, prefix_length - 1, range_low, range_length, is_lower, is_out_of_band) } /// Read a custom Huffman table from the bitstream (B.2 "Decoding a code table"). @@ -239,31 +223,18 @@ impl HuffmanTable { bail!(HuffmanError::InvalidCode); } // a) "Read HTPS bits. Set PREFLEN[NTEMP] to the value decoded." - let prefix_length = reader - .read_bits(prefix_length_bits) - .ok_or(HuffmanError::InvalidCode)? as u8; + let prefix_length = reader.read_bits(prefix_length_bits).ok_or(HuffmanError::InvalidCode)? as u8; // b) "Read HTRS bits. Let RANGELEN[NTEMP] be the value decoded." - let range_length = reader - .read_bits(range_length_bits) - .ok_or(HuffmanError::InvalidCode)? as u8; + let range_length = reader.read_bits(range_length_bits).ok_or(HuffmanError::InvalidCode)? as u8; // c) "Set: RANGELOW[NTEMP] = CURRANGELOW // CURRANGELOW = CURRANGELOW + 2^RANGELEN[NTEMP] // NTEMP = NTEMP + 1" - lines.push(TableLine::new( - current_range_low, - prefix_length, - range_length, - )); + lines.push(TableLine::new(current_range_low, prefix_length, range_length)); - let range_size = 1_i64 - .checked_shl(range_length as u32) - .ok_or(HuffmanError::InvalidCode)?; - let next_range_low = (current_range_low as i64) - .checked_add(range_size) - .ok_or(HuffmanError::InvalidCode)?; - current_range_low = - i32::try_from(next_range_low).map_err(|_| HuffmanError::InvalidCode)?; + let range_size = 1_i64.checked_shl(range_length as u32).ok_or(HuffmanError::InvalidCode)?; + let next_range_low = (current_range_low as i64).checked_add(range_size).ok_or(HuffmanError::InvalidCode)?; + current_range_low = i32::try_from(next_range_low).map_err(|_| HuffmanError::InvalidCode)?; } // 6) "Read HTPS bits. Let LOWPREFLEN be the value read." @@ -271,12 +242,8 @@ impl HuffmanTable { // RANGELOW[NTEMP] = HTLOW − 1, NTEMP = NTEMP + 1 // This is the lower range table line for this table." lines.push(TableLine::lower( - minimum_value - .checked_sub(1) - .ok_or(HuffmanError::InvalidCode)?, - reader - .read_bits(prefix_length_bits) - .ok_or(HuffmanError::InvalidCode)? as u8, + minimum_value.checked_sub(1).ok_or(HuffmanError::InvalidCode)?, + reader.read_bits(prefix_length_bits).ok_or(HuffmanError::InvalidCode)? as u8, 32, )); @@ -284,24 +251,14 @@ impl HuffmanTable { // 9) "Set: PREFLEN[NTEMP] = HIGHPREFLEN, RANGELEN[NTEMP] = 32, // RANGELOW[NTEMP] = HTHIGH, NTEMP = NTEMP + 1 // This is the upper range table line for this table." - lines.push(TableLine::upper( - current_range_low, - reader - .read_bits(prefix_length_bits) - .ok_or(HuffmanError::InvalidCode)? as u8, - 32, - )); + lines.push(TableLine::upper(current_range_low, reader.read_bits(prefix_length_bits).ok_or(HuffmanError::InvalidCode)? as u8, 32)); // 10) "If HTOOB is 1, then: // a) Read HTPS bits. Let OOBPREFLEN be the value read. // b) Set: PREFLEN[NTEMP] = OOBPREFLEN, NTEMP = NTEMP + 1 // This is the out-of-band table line for this table." if has_out_of_band { - lines.push(TableLine::oob( - reader - .read_bits(prefix_length_bits) - .ok_or(HuffmanError::InvalidCode)? as u8, - )); + lines.push(TableLine::oob(reader.read_bits(prefix_length_bits).ok_or(HuffmanError::InvalidCode)? as u8)); } // 11) "Create the prefix codes using the algorithm described in B.3." @@ -328,46 +285,22 @@ pub(crate) struct TableLine { impl TableLine { /// Create a normal table line. pub(crate) const fn new(range_low: i32, prefix_length: u8, range_length: u8) -> Self { - Self { - range_low, - prefix_length, - range_length, - is_lower: false, - is_out_of_band: false, - } + Self { range_low, prefix_length, range_length, is_lower: false, is_out_of_band: false } } /// Create a lower range line (-∞...`range_high`). const fn lower(range_high: i32, prefix_length: u8, range_length: u8) -> Self { - Self { - range_low: range_high, - prefix_length, - range_length, - is_lower: true, - is_out_of_band: false, - } + Self { range_low: range_high, prefix_length, range_length, is_lower: true, is_out_of_band: false } } /// Create an upper range line (`range_low`...+∞). const fn upper(range_low: i32, prefix_length: u8, range_length: u8) -> Self { - Self { - range_low, - prefix_length, - range_length, - is_lower: false, - is_out_of_band: false, - } + Self { range_low, prefix_length, range_length, is_lower: false, is_out_of_band: false } } /// Create an out-of-band marker line. const fn oob(prefix_length: u8) -> Self { - Self { - range_low: 0, - prefix_length, - range_length: 0, - is_lower: false, - is_out_of_band: true, - } + Self { range_low: 0, prefix_length, range_length: 0, is_lower: false, is_out_of_band: true } } } @@ -375,10 +308,7 @@ impl TableLine { #[derive(Debug, Clone, Copy)] enum HuffmanNode { /// Intermediate node. - Intermediate { - zero: Option, - one: Option, - }, + Intermediate { zero: Option, one: Option }, /// Leaf node. Leaf(LeafData), /// Empty node (padding to fill fixed-size arrays in inline tables). @@ -387,19 +317,11 @@ enum HuffmanNode { impl HuffmanNode { fn new_intermediate() -> Self { - Self::Intermediate { - zero: None, - one: None, - } + Self::Intermediate { zero: None, one: None } } fn new_leaf(range_low: i32, range_length: u8, is_lower: bool, is_out_of_band: bool) -> Self { - Self::Leaf(LeafData { - range_low, - range_length, - is_lower, - is_out_of_band, - }) + Self::Leaf(LeafData { range_low, range_length, is_lower, is_out_of_band }) } /// Get the child index for a given bit (0 or 1). @@ -417,11 +339,7 @@ impl HuffmanNode { } /// Set the child index for a given bit (0 or 1). - fn set_child( - &mut self, - child_zero: bool, - index: NonZeroU32, - ) -> core::result::Result<(), HuffmanError> { + fn set_child(&mut self, child_zero: bool, index: NonZeroU32) -> core::result::Result<(), HuffmanError> { match self { Self::Intermediate { zero, one } => { if child_zero { @@ -436,11 +354,7 @@ impl HuffmanNode { } /// Implements B.4 "Using a Huffman table". - fn decode_from( - nodes: &[Self], - mut node_index: u32, - reader: &mut Reader<'_>, - ) -> Result> { + fn decode_from(nodes: &[Self], mut node_index: u32, reader: &mut Reader<'_>) -> Result> { // 1) "Read one bit at a time until the bit string read matches the code assigned to // one of the table lines." loop { @@ -459,20 +373,13 @@ impl HuffmanNode { // 2) "Read RANGELEN[I] bits. Let HTOFFSET be the value read." // `HTOFFSET` - let range_offset = reader - .read_bits(leaf.range_length) - .ok_or(HuffmanError::InvalidCode)? - as i32; + let range_offset = reader.read_bits(leaf.range_length).ok_or(HuffmanError::InvalidCode)? as i32; // 4) "Otherwise, if table line I is the lower range table line for this // table, then set: HTVAL = RANGELOW[I] − HTOFFSET" // 5) "Otherwise, set: HTVAL = RANGELOW[I] + HTOFFSET" // `HTVAL`. Wrapping: a range line's offset can take it past what an `i32` holds. - let value = if leaf.is_lower { - leaf.range_low.wrapping_sub(range_offset) - } else { - leaf.range_low.wrapping_add(range_offset) - }; + let value = if leaf.is_lower { leaf.range_low.wrapping_sub(range_offset) } else { leaf.range_low.wrapping_add(range_offset) }; return Ok(Some(value)); } @@ -502,17 +409,10 @@ struct LeafData { /// This can be either an inline table (fixed-size array for standard tables) /// or a dynamic table (Vec for runtime-built custom tables). #[derive(Debug, Clone)] -#[allow( - clippy::large_enum_variant, - reason = "Inline variant is expected to be large." -)] +#[allow(clippy::large_enum_variant, reason = "Inline variant is expected to be large.")] enum InnerHuffmanTable { - Inline { - nodes: [HuffmanNode; INLINE_TABLE_SIZE], - }, - Dynamic { - nodes: Vec, - }, + Inline { nodes: [HuffmanNode; INLINE_TABLE_SIZE] }, + Dynamic { nodes: Vec }, } /// Standard Huffman tables (`TABLE_A` through `TABLE_O`). diff --git a/vendor/hayro-jbig2/src/integer_decoder.rs b/vendor/hayro-jbig2/src/integer_decoder.rs index 7f9f7831a..f07d65461 100644 --- a/vendor/hayro-jbig2/src/integer_decoder.rs +++ b/vendor/hayro-jbig2/src/integer_decoder.rs @@ -38,10 +38,7 @@ impl IntegerDecoder { let s = self.decode_bit(decoder, &mut prev); // `V` - Magnitude value, decoded according to Figure A.1 flowchart. - #[expect( - clippy::same_functions_in_if_condition, - reason = "each call mutates `prev`" - )] + #[expect(clippy::same_functions_in_if_condition, reason = "each call mutates `prev`")] let v = if self.decode_bit(decoder, &mut prev) == 0 { // Figure A.1: "V = next 2 bits" self.decode_n_bits(decoder, &mut prev, 2) @@ -59,8 +56,7 @@ impl IntegerDecoder { self.decode_n_bits(decoder, &mut prev, 12) + 340 } else { // Figure A.1: "V = (next 32 bits) + 4436" - self.decode_n_bits(decoder, &mut prev, 32) - .wrapping_add(4436) + self.decode_n_bits(decoder, &mut prev, 32).wrapping_add(4436) }; // A.2: "The result of the integer arithmetic decoding procedure is equal to: @@ -103,12 +99,7 @@ impl IntegerDecoder { /// Decode `n` bits and update `PREV` for each. #[inline(always)] - fn decode_n_bits( - &mut self, - decoder: &mut ArithmeticDecoder<'_>, - prev: &mut u32, - n: usize, - ) -> u32 { + fn decode_n_bits(&mut self, decoder: &mut ArithmeticDecoder<'_>, prev: &mut u32, n: usize) -> u32 { let mut value = 0_u32; for _ in 0..n { let bit = self.decode_bit(decoder, prev); diff --git a/vendor/hayro-jbig2/src/integration.rs b/vendor/hayro-jbig2/src/integration.rs index 70df0f42d..24fda3546 100644 --- a/vendor/hayro-jbig2/src/integration.rs +++ b/vendor/hayro-jbig2/src/integration.rs @@ -80,11 +80,7 @@ impl Jbig2Decoder { let image = Image::new(&input)?; - Ok(Self { - width: image.width(), - height: image.height(), - input, - }) + Ok(Self { width: image.width(), height: image.height(), input }) } } @@ -140,10 +136,7 @@ pub fn register_decoding_hook() -> bool { } for extension in ["jbig2", "jb2"] { - image::hooks::register_decoding_hook( - extension.into(), - Box::new(|r| Ok(Box::new(Jbig2Decoder::new(r)?))), - ); + image::hooks::register_decoding_hook(extension.into(), Box::new(|r| Ok(Box::new(Jbig2Decoder::new(r)?)))); register_format_detection_hook(extension.into(), JBIG2_MAGIC, None); } diff --git a/vendor/hayro-jbig2/src/lib.rs b/vendor/hayro-jbig2/src/lib.rs index 6ec7fd83f..b1176d8ff 100644 --- a/vendor/hayro-jbig2/src/lib.rs +++ b/vendor/hayro-jbig2/src/lib.rs @@ -73,15 +73,9 @@ mod symbol_id_decoder; mod pdfcraft_tests; use error::bail; -pub use error::{ - DecodeError, FormatError, HuffmanError, OverflowError, ParseError, RegionError, Result, - SegmentError, SymbolError, TemplateError, -}; +pub use error::{DecodeError, FormatError, HuffmanError, OverflowError, ParseError, RegionError, Result, SegmentError, SymbolError, TemplateError}; -use crate::file::{ - FileOrganization, SegmentCount, after_file_header, parse_segments_random_access, - parse_segments_sequential, -}; +use crate::file::{FileOrganization, SegmentCount, after_file_header, parse_segments_random_access, parse_segments_sequential}; use bitmap::Bitmap; use decode::CombinationOperator; use decode::generic; @@ -161,10 +155,7 @@ impl<'a> Image<'a> { .max(); // Find and parse page information to extract dimensions. - let page_info_seg = segments - .iter() - .find(|s| s.header.segment_type == SegmentType::PageInformation) - .ok_or(FormatError::MissingPageInfo)?; + let page_info_seg = segments.iter().find(|s| s.header.segment_type == SegmentType::PageInformation).ok_or(FormatError::MissingPageInfo)?; let mut reader = Reader::new(page_info_seg.data); let page_info = parse_page_information(&mut reader)?; @@ -172,23 +163,14 @@ impl<'a> Image<'a> { // "A page's bitmap height may be declared in its page information segment // to be unknown (by specifying a height of 0xFFFFFFFF). In this case, the // page must be striped." (7.4.8.2) - let height = if page_info.height == 0xFFFF_FFFF { - height_from_stripes.ok_or(FormatError::UnknownPageHeight)? - } else { - page_info.height - }; + let height = if page_info.height == 0xFFFF_FFFF { height_from_stripes.ok_or(FormatError::UnknownPageHeight)? } else { page_info.height }; if page_info.width == 0 || height == 0 { bail!(FormatError::EmptyPage); } bitmap::check_page_size(page_info.width, height)?; - Ok(Self { - segments, - width: page_info.width, - height, - height_from_stripes, - }) + Ok(Self { segments, width: page_info.width, height, height_from_stripes }) } /// The width of the image in pixels. @@ -345,17 +327,9 @@ fn decode_segments( work_left: &mut u64, ) -> Result<()> { // Find and parse page information segment first. - if let Some(page_info) = segments - .iter() - .find(|s| s.header.segment_type == SegmentType::PageInformation) - { + if let Some(page_info) = segments.iter().find(|s| s.header.segment_type == SegmentType::PageInformation) { let mut reader = Reader::new(page_info.data); - init_page( - &mut reader, - height_from_stripes, - &mut decoder_ctx.page_state, - &mut decoder_ctx.page_bitmap, - )?; + init_page(&mut reader, height_from_stripes, &mut decoder_ctx.page_state, &mut decoder_ctx.page_bitmap)?; } else { bail!(FormatError::MissingPageInfo); } @@ -406,13 +380,8 @@ fn decode_segments( charge_work(work_left, input_symbols.len() as u64)?; // Collect Huffman tables from referred table segments. - let referred_tables: Vec = seg - .header - .referred_to_segments - .iter() - .filter_map(|&num| page_state.get_huffman_table(num)) - .cloned() - .collect(); + let referred_tables: Vec = + seg.header.referred_to_segments.iter().filter_map(|&num| page_state.get_huffman_table(num)).cloned().collect(); // Get retained contexts from the last referred symbol dictionary (7.4.2.2 step 3). let retained_contexts = seg @@ -442,13 +411,8 @@ fn decode_segments( // Collect Huffman tables from referred table segments. // "These user-supplied Huffman decoding tables may be supplied either // as a Tables segment..." (7.4.3.1.6) - let referred_tables: Vec = seg - .header - .referred_to_segments - .iter() - .filter_map(|&num| page_state.get_huffman_table(num)) - .cloned() - .collect(); + let referred_tables: Vec = + seg.header.referred_to_segments.iter().filter_map(|&num| page_state.get_huffman_table(num)).cloned().collect(); let header = text::parse(&mut reader, symbols.len() as u32)?; charge_work(work_left, bitmap::copy_work(header.region_info.width, header.region_info.height))?; @@ -457,29 +421,10 @@ fn decode_segments( charge_work(work_left, (symbols.len() as u64).saturating_mul(bitmap::HUFFMAN_LINE_WORK))?; } - if page_state.can_decode_directly( - page_bitmap, - &header.region_info, - header.flags.default_pixel, - ) { - text::decode_into( - &header, - &symbols, - &referred_tables, - &page_state.standard_tables, - page_bitmap, - scratch_buffers, - work_left, - )?; + if page_state.can_decode_directly(page_bitmap, &header.region_info, header.flags.default_pixel) { + text::decode_into(&header, &symbols, &referred_tables, &page_state.standard_tables, page_bitmap, scratch_buffers, work_left)?; } else { - let region = text::decode( - &header, - &symbols, - &referred_tables, - &page_state.standard_tables, - scratch_buffers, - work_left, - )?; + let region = text::decode(&header, &symbols, &referred_tables, &page_state.standard_tables, scratch_buffers, work_left)?; page_bitmap.combine_region(®ion.bitmap, region.combination_operator); } page_state.page_pristine = false; @@ -490,13 +435,8 @@ fn decode_segments( charge_work(work_left, symbols.len() as u64)?; // Collect Huffman tables from referred table segments. - let referred_tables: Vec = seg - .header - .referred_to_segments - .iter() - .filter_map(|&num| page_state.get_huffman_table(num)) - .cloned() - .collect(); + let referred_tables: Vec = + seg.header.referred_to_segments.iter().filter_map(|&num| page_state.get_huffman_table(num)).cloned().collect(); let header = text::parse(&mut reader, symbols.len() as u32)?; charge_work(work_left, bitmap::copy_work(header.region_info.width, header.region_info.height))?; @@ -504,14 +444,7 @@ fn decode_segments( // Its symbol ID table has a line for each symbol. charge_work(work_left, (symbols.len() as u64).saturating_mul(bitmap::HUFFMAN_LINE_WORK))?; } - let region = text::decode( - &header, - &symbols, - &referred_tables, - &page_state.standard_tables, - scratch_buffers, - work_left, - )?; + let region = text::decode(&header, &symbols, &referred_tables, &page_state.standard_tables, scratch_buffers, work_left)?; page_state.store_region(seg.header.segment_number, region.bitmap)?; } SegmentType::ImmediateHalftoneRegion | SegmentType::ImmediateLosslessHalftoneRegion => { @@ -525,11 +458,7 @@ fn decode_segments( let header = halftone::parse(&mut reader)?; charge_work(work_left, halftone::work(&header, pattern_dict))?; - if page_state.can_decode_directly( - page_bitmap, - &header.region_info, - header.flags.initial_pixel_color, - ) { + if page_state.can_decode_directly(page_bitmap, &header.region_info, header.flags.initial_pixel_color) { halftone::decode_into(&header, pattern_dict, page_bitmap, scratch_buffers)?; } else { let region = halftone::decode(&header, pattern_dict, scratch_buffers)?; @@ -552,11 +481,7 @@ fn decode_segments( } SegmentType::IntermediateGenericRefinementRegion => { // Same logic as immediate refinement, but store result instead of combining. - let referred_segment = seg - .header - .referred_to_segments - .first() - .and_then(|&num| page_state.get_referred_segment(num)); + let referred_segment = seg.header.referred_to_segments.first().and_then(|&num| page_state.get_referred_segment(num)); let header = generic_refinement::parse(&mut reader)?; charge_work(work_left, region_work(&header.region_info))?; @@ -572,18 +497,13 @@ fn decode_segments( let region = generic_refinement::decode(&header, reference, scratch_buffers)?; page_state.store_region(seg.header.segment_number, region.bitmap)?; } - SegmentType::ImmediateGenericRefinementRegion - | SegmentType::ImmediateLosslessGenericRefinementRegion => { + SegmentType::ImmediateGenericRefinementRegion | SegmentType::ImmediateLosslessGenericRefinementRegion => { // "3) Determine the buffer associated with the region segment that // this segment refers to." (7.4.7.5) // // With no region segment referred to, the reference is the page restricted to // this segment's area (7.4.7.4). - let referred_segment = seg - .header - .referred_to_segments - .first() - .and_then(|&num| page_state.get_referred_segment(num)); + let referred_segment = seg.header.referred_to_segments.first().and_then(|&num| page_state.get_referred_segment(num)); let header = generic_refinement::parse(&mut reader)?; charge_work(work_left, region_work(&header.region_info))?; @@ -591,12 +511,7 @@ fn decode_segments( if let Some(referred_segment) = referred_segment && page_state.can_decode_directly(page_bitmap, &header.region_info, false) { - generic_refinement::decode_into( - &header, - referred_segment, - page_bitmap, - scratch_buffers, - )?; + generic_refinement::decode_into(&header, referred_segment, page_bitmap, scratch_buffers)?; } else { // PdfCraft patch: a refinement of the page refines its area (`Bitmap::area`). let area; @@ -639,8 +554,7 @@ const ENTRY_WORDS: u64 = 32; /// square region of typical rows), and a few kilobytes could exhaust memory. A segment being /// decoded takes more for a while, within its own bounds: the page bitmap isn't counted, nor is /// what a region or a grid uses until it is stored or freed. -const MAX_RETAINED_WORDS: u64 = - 2 * (bitmap::MAX_PIXELS / bitmap::WORD_BITS as u64 + bitmap::BITMAP_WORDS as u64 + ENTRY_WORDS); +const MAX_RETAINED_WORDS: u64 = 2 * (bitmap::MAX_PIXELS / bitmap::WORD_BITS as u64 + bitmap::BITMAP_WORDS as u64 + ENTRY_WORDS); /// PdfCraft patch: the most symbols one segment may refer to, 2^20, far beyond the 65,535 a /// dictionary may export. References may repeat, so each names the same symbols again: without @@ -683,12 +597,7 @@ impl PageState { } /// Check if an immediate region can be decoded directly into the page bitmap. - fn can_decode_directly( - &self, - page_bitmap: &Bitmap, - region_info: &decode::RegionSegmentInfo, - region_default_pixel: bool, - ) -> bool { + fn can_decode_directly(&self, page_bitmap: &Bitmap, region_info: &decode::RegionSegmentInfo, region_default_pixel: bool) -> bool { if !self.page_pristine { return false; } @@ -740,10 +649,7 @@ impl PageState { /// Look up a referred segment by number. fn get_referred_segment(&self, segment_number: u32) -> Option<&Bitmap> { - self.referred_segments - .binary_search_by_key(&segment_number, |(num, _)| *num) - .ok() - .map(|idx| &self.referred_segments[idx].1) + self.referred_segments.binary_search_by_key(&segment_number, |(num, _)| *num).ok().map(|idx| &self.referred_segments[idx].1) } /// Store a decoded pattern dictionary for later reference. @@ -755,10 +661,7 @@ impl PageState { /// Look up a pattern dictionary by segment number. fn get_pattern_dictionary(&self, segment_number: u32) -> Option<&PatternDictionary> { - self.pattern_dictionaries - .binary_search_by_key(&segment_number, |(num, _)| *num) - .ok() - .map(|idx| &self.pattern_dictionaries[idx].1) + self.pattern_dictionaries.binary_search_by_key(&segment_number, |(num, _)| *num).ok().map(|idx| &self.pattern_dictionaries[idx].1) } /// Store a decoded symbol dictionary for later reference. @@ -772,9 +675,7 @@ impl PageState { /// [`MAX_REFERRED_SYMBOLS`] before anything is collected. fn referred_symbols(&self, segments: &[u32]) -> Result> { let dictionaries = || segments.iter().filter_map(|&num| self.get_symbol_dictionary(num)); - let count = dictionaries() - .map(|dictionary| dictionary.exported_symbols.len() as u64) - .fold(0, u64::saturating_add); + let count = dictionaries().map(|dictionary| dictionary.exported_symbols.len() as u64).fold(0, u64::saturating_add); if count > MAX_REFERRED_SYMBOLS { bail!(OverflowError::SymbolCount); } @@ -783,10 +684,7 @@ impl PageState { /// Look up a symbol dictionary by segment number. fn get_symbol_dictionary(&self, segment_number: u32) -> Option<&SymbolDictionary> { - self.symbol_dictionaries - .binary_search_by_key(&segment_number, |(num, _)| *num) - .ok() - .map(|idx| &self.symbol_dictionaries[idx].1) + self.symbol_dictionaries.binary_search_by_key(&segment_number, |(num, _)| *num).ok().map(|idx| &self.symbol_dictionaries[idx].1) } /// Store a decoded Huffman table for later reference. @@ -798,30 +696,18 @@ impl PageState { /// Look up a Huffman table by segment number. fn get_huffman_table(&self, segment_number: u32) -> Option<&HuffmanTable> { - self.huffman_tables - .binary_search_by_key(&segment_number, |(num, _)| *num) - .ok() - .map(|idx| &self.huffman_tables[idx].1) + self.huffman_tables.binary_search_by_key(&segment_number, |(num, _)| *num).ok().map(|idx| &self.huffman_tables[idx].1) } } /// Parse page information and initialize the page bitmap. -fn init_page( - reader: &mut Reader<'_>, - height_from_stripes: Option, - page: &mut PageState, - bitmap: &mut Bitmap, -) -> Result<()> { +fn init_page(reader: &mut Reader<'_>, height_from_stripes: Option, page: &mut PageState, bitmap: &mut Bitmap) -> Result<()> { let page_info = parse_page_information(reader)?; // "A page's bitmap height may be declared in its page information segment // to be unknown (by specifying a height of 0xFFFFFFFF). In this case, the // page must be striped." (7.4.8.2) - let height = if page_info.height == 0xFFFF_FFFF { - height_from_stripes.ok_or(FormatError::UnknownPageHeight)? - } else { - page_info.height - }; + let height = if page_info.height == 0xFFFF_FFFF { height_from_stripes.ok_or(FormatError::UnknownPageHeight)? } else { page_info.height }; // "Bit 2: Page default pixel value. This bit contains the initial value // for every pixel in the page, before any region segments are decoded @@ -908,10 +794,7 @@ mod tests { // An immediate refinement of the page, which reads the page at its own location (7.4.7.4). vec![segment(1, 42, &[], ®ion_of_4(x, y, REPLACE, REFINEMENT))], // An immediate refinement of an intermediate region at the same place (7.4.7.5). - vec![ - segment(1, 36, &[], ®ion_of_4(x, y, OR, GENERIC)), - segment(2, 42, &[1], ®ion_of_4(x, y, OR, REFINEMENT)), - ], + vec![segment(1, 36, &[], ®ion_of_4(x, y, OR, GENERIC)), segment(2, 42, &[1], ®ion_of_4(x, y, OR, REFINEMENT))], ]; forms.map(|form| { let stream = [page_of_8(), form.concat()].concat(); @@ -1008,7 +891,9 @@ mod tests { // A page of bit(1, ..), and over it at 41, 4 the area refined from it. const PAGE: &str = "000000003000010000001300000070000000180000000000000000420000000000012600010000016f00000070000000180000000000000000040003fffdff02fefefefb5d354db053c2a984c01af66c619b02c245055be23a2a431b04c60325c88676f6ff1b0a68c873ad9011a27a89fc99abc7db2e8f529ecf198ff8c6a726ddcb746dc51f3812e365e74ee668fa02f59182cae39f0ef43b3201da1bcd43a21f449889e15ba0ba1a9344da1bdb9dcb4015279a39d944509febc622a235fa2c623acb443f0c10dabf7fba5e9d6fef2f1289dfd0a6a3801d036f21a62045074f5d3158ab0373ad2334102ef867dc3132dc8d02fe517771c419cdbad47d67d409ec89d0425d1f51a48af6ba3bee6e0701185bfa5f46b347b0ec39e744b665d1e8aac868838d3db25162d65534ff4771d9c0d657bd48d5814fa7cc184d0e961defab2d75a79a88345cdae5546a54221a22ddfe9c8a0514f32ac9de806fbc5fb4f5275c79d679f0258f77900daaa273cee50e50c958f323414670d7761418639342fdb2082eac5e7934f1a06169991452b1a042eaee7871ffac000000022a000100000091000000400000001000000029000000040400ffffffffd24567306e52f57232cefa9800db00fb60c21b30b0e53d9fac8a1f863a580a7cc49ab401934ac8be3a18e2dc0f01774b76c3e9196283cb5504742c763a867bc1aae8c48d74d194dacda03ce7e91904897ab61add273d9188fda65dc6fefb995d85f48142e43c1970bedb9c5f4be3cb00d458e9f4ee9714a61fffac"; let page: Vec> = (0..24) - .map(|y| (0..112).map(|x| bit(1, x, y) ^ if (41..105).contains(&x) && (4..20).contains(&y) { flipped(10, x - 41, y - 4) } else { 0 }).collect()) + .map(|y| { + (0..112).map(|x| bit(1, x, y) ^ if (41..105).contains(&x) && (4..20).contains(&y) { flipped(10, x - 41, y - 4) } else { 0 }).collect() + }) .collect(); // A symbol of bit(3, ..), and a text instance refined from it, 70 narrower with RDX 0. const TEXT: &str = "0000000030000100000013000000460000000c000000000000000042000000000001000001000000ed000003fffdff02fefefe00000001000000013f4efc0ce48e6b5c00246a648400fb605a44d542ed29da2b9b55c01f4e5af9842dd70c88f4913c7f552503ba52a5d7b5d9fd08ff5794b4dbfb3df7bafcf9c43d04154c1cefa181ca1aba5da826a4e4229858bd0950442df69c098ab3b61a32f71b136974b96bcb5306f3e75af1a4ef51b8f56a355acb8b69915cfa623f5a21933be8c056a348783a116ea914e886af2c64bf3b23e5610726c981092220f05411857529861fbf4c630a15fd00b081d2351279e06602f4408b25dc1d01c223027ecb8c87c4b1d76e3882a759c1adaf749f0e20735f8bd5a7306fffac000000020620010100000085000000460000000c0000000000000000040012ffffffff00000001a967c0b129999147062a4766ce10bc3dae7f1daf43dda1427d31203a1bc9fa021e0504e0a4b01739952970b54ad11ac08c0684d2f556a1843eb01dc75b963be6237b7f02fdfe17ccf7f061de310a936fd08c5ddea47609789e55f7cbca81ae38219c4abc5f9eff47ffac"; @@ -1088,9 +973,8 @@ mod tests { let flipped = |seed: u32, x: u32, y: u32| bit(seed, x, y) & bit(seed + 1, x, y) & bit(seed + 2, x, y); // A symbol of bit(2, ..), and a text instance refined from it, 4 wider with RDX 0. const TEXT: &str = "0000000030000100000013000000680000000c000000000000000042000000000001000001000000b1000003fffdff02fefefe00000001000000013f525ad7118f669a303f1b11efa5210e9765b834b1831c650f3a3d325dbd7317379ea4fb573b09a20c362f065d8f9301e74cbbc50c69910641c0e0eea7c2fd1e831ca1459a943be55ed8e074b426ad7ff1e8d8ff6f1aa44684de5da4b4c3483911604412e00e96a0db6ec7103feb2bc4301ae98d3f9c23078ae72dc46f76e9dfea209d39187f1194f7b9285cd6e7b2dc7abb5def43ff0abe2df554fc55ffac0000000206200101000000af000000680000000c0000000000000000040012ffffffff00000001a96b5febebec5a68693b51f5db25ddf176d4aae89904a71d1690f12888e10b038db723ac59941f76c2844b739ce524d9563f4005e1edbabf2e323e8e9ac1a3b9060587c3010e7d6bcf90c00dbf9000a2f17b1d9b598e01b9158dc16a63f4388a6f647b99dc7118aa09e08d59fba1bc24e3a0f1ebb0cae636b6bedbb65b01945228d3e5d2980a0ad6290c13d2f34f5c861415ffac"; - let picture: Vec> = (0..12) - .map(|y| (0..104).map(|x| (if (2..102).contains(&x) { bit(2, x - 2, y) } else { 0 }) ^ flipped(20, x, y)).collect()) - .collect(); + let picture: Vec> = + (0..12).map(|y| (0..104).map(|x| (if (2..102).contains(&x) { bit(2, x - 2, y) } else { 0 }) ^ flipped(20, x, y)).collect()).collect(); let stream: Vec = (0..TEXT.len() / 2).map(|i| u8::from_str_radix(&TEXT[i * 2..i * 2 + 2], 16).unwrap()).collect(); let mut rows = Rows::default(); Image::new_embedded(&stream, None).unwrap().decode(&mut rows).unwrap(); diff --git a/vendor/hayro-jbig2/src/page_info.rs b/vendor/hayro-jbig2/src/page_info.rs index cc0c89c06..cb22c445b 100644 --- a/vendor/hayro-jbig2/src/page_info.rs +++ b/vendor/hayro-jbig2/src/page_info.rs @@ -93,19 +93,11 @@ pub(crate) fn parse_page_information(reader: &mut Reader<'_>) -> Result) -> Result PageFlags { diff --git a/vendor/hayro-jbig2/src/pdfcraft_tests.rs b/vendor/hayro-jbig2/src/pdfcraft_tests.rs index cd96db6c9..0c00c8ebd 100644 --- a/vendor/hayro-jbig2/src/pdfcraft_tests.rs +++ b/vendor/hayro-jbig2/src/pdfcraft_tests.rs @@ -649,7 +649,8 @@ fn jbig2_symbol_dictionaries_that_never_advance_terminate() { } let _ = tx.send(()); }); - rx.recv_timeout(std::time::Duration::from_secs(20)).unwrap_or_else(|_| panic!("{what}: a JBIG2 symbol dictionary must not stall the decoder")); + rx.recv_timeout(std::time::Duration::from_secs(20)) + .unwrap_or_else(|_| panic!("{what}: a JBIG2 symbol dictionary must not stall the decoder")); } } @@ -716,4 +717,3 @@ fn jbig2_placements_at_the_end_of_an_i32_draw_nothing() { assert_eq!(ink(hex(UPPER_LINE), 16, 12), 0, "an upper range line past an i32"); assert_eq!(ink(hex(LOWER_LINE), 16, 12), 0, "a lower range line past an i32"); } - diff --git a/vendor/hayro-jbig2/src/segment.rs b/vendor/hayro-jbig2/src/segment.rs index 1c6fcf31e..ccf86e968 100644 --- a/vendor/hayro-jbig2/src/segment.rs +++ b/vendor/hayro-jbig2/src/segment.rs @@ -204,9 +204,7 @@ pub(crate) fn parse_segment_header(reader: &mut Reader<'_>) -> Result) -> Result(reader: &mut Reader<'a>) -> Result> /// may contain the value 0xFFFFFFFF. This value is intended to mean that the /// length of the segment's data part is unknown at the time that the segment /// header is written." (7.2.7) -pub(crate) fn parse_segment_data<'a>( - reader: &mut Reader<'a>, - header: SegmentHeader, -) -> Result> { +pub(crate) fn parse_segment_data<'a>(reader: &mut Reader<'a>, header: SegmentHeader) -> Result> { let data = if let Some(len) = header.data_length { - reader - .read_bytes(len as usize) - .ok_or(ParseError::UnexpectedEof)? + reader.read_bytes(len as usize).ok_or(ParseError::UnexpectedEof)? } else { // "In order for the decoder to correctly decode the segment, it needs to // read the four-byte row count field, which is stored in the last four @@ -420,10 +409,7 @@ mod tests { // two bytes, since this segment's number is between 256 and 65535. The segments // that it refers to are, in decimal, numbers 256, 2, 30, 5, 512, 513, 514, 515, // and 516." - assert_eq!( - header.referred_to_segments, - vec![256, 2, 30, 5, 512, 513, 514, 515, 516] - ); + assert_eq!(header.referred_to_segments, vec![256, 2, 30, 5, 512, 513, 514, 515, 516]); // "00 00 04 01: This segment is associated with page number 1025." assert_eq!(header._page_association, 1025); @@ -448,9 +434,6 @@ mod tests { let mut reader = Reader::new(&data); let error = parse_segment_header(&mut reader).unwrap_err(); - assert!(matches!( - error, - DecodeError::Segment(SegmentError::InvalidReferredCount) - )); + assert!(matches!(error, DecodeError::Segment(SegmentError::InvalidReferredCount))); } } diff --git a/vendor/hayro-jbig2/src/simd.rs b/vendor/hayro-jbig2/src/simd.rs index 2bd1adb7e..bf95c4a92 100644 --- a/vendor/hayro-jbig2/src/simd.rs +++ b/vendor/hayro-jbig2/src/simd.rs @@ -18,9 +18,7 @@ mod inner { impl mask32x8 { #[inline(always)] pub(crate) fn select(self, if_true: u32x8, if_false: u32x8) -> u32x8 { - u32x8 { - inner: self.inner.select(if_true.inner, if_false.inner), - } + u32x8 { inner: self.inner.select(if_true.inner, if_false.inner) } } } @@ -34,16 +32,12 @@ mod inner { impl u32x8 { #[inline(always)] pub(crate) fn from_slice(simd: S, slice: &[u32]) -> Self { - Self { - inner: fearless_simd::u32x8::from_slice(simd, &slice[..SIMD_WIDTH]), - } + Self { inner: fearless_simd::u32x8::from_slice(simd, &slice[..SIMD_WIDTH]) } } #[inline(always)] pub(crate) fn splat(simd: S, val: u32) -> Self { - Self { - inner: fearless_simd::u32x8::splat(simd, val), - } + Self { inner: fearless_simd::u32x8::splat(simd, val) } } #[inline(always)] @@ -53,9 +47,7 @@ mod inner { #[inline(always)] pub(crate) fn simd_gt(self, other: Self) -> mask32x8 { - mask32x8 { - inner: self.inner.simd_gt(other.inner), - } + mask32x8 { inner: self.inner.simd_gt(other.inner) } } } @@ -63,9 +55,7 @@ mod inner { type Output = Self; #[inline(always)] fn bitand(self, rhs: Self) -> Self { - Self { - inner: self.inner & rhs.inner, - } + Self { inner: self.inner & rhs.inner } } } @@ -73,9 +63,7 @@ mod inner { type Output = Self; #[inline(always)] fn bitor(self, rhs: Self) -> Self { - Self { - inner: self.inner | rhs.inner, - } + Self { inner: self.inner | rhs.inner } } } @@ -83,9 +71,7 @@ mod inner { type Output = Self; #[inline(always)] fn bitxor(self, rhs: Self) -> Self { - Self { - inner: self.inner ^ rhs.inner, - } + Self { inner: self.inner ^ rhs.inner } } } @@ -140,16 +126,9 @@ mod inner { pub(crate) fn select(self, if_true: u32x8, if_false: u32x8) -> u32x8 { let mut result = [0u32; SIMD_WIDTH]; for i in 0..SIMD_WIDTH { - result[i] = if self.val[i] { - if_true.val[i] - } else { - if_false.val[i] - }; - } - u32x8 { - val: result, - _marker: PhantomData, + result[i] = if self.val[i] { if_true.val[i] } else { if_false.val[i] }; } + u32x8 { val: result, _marker: PhantomData } } } @@ -166,18 +145,12 @@ mod inner { pub(crate) fn from_slice(_simd: S, slice: &[u32]) -> Self { let mut val = [0u32; SIMD_WIDTH]; val.copy_from_slice(&slice[..SIMD_WIDTH]); - Self { - val, - _marker: PhantomData, - } + Self { val, _marker: PhantomData } } #[inline(always)] pub(crate) fn splat(_simd: S, val: u32) -> Self { - Self { - val: [val; SIMD_WIDTH], - _marker: PhantomData, - } + Self { val: [val; SIMD_WIDTH], _marker: PhantomData } } #[inline(always)] @@ -191,10 +164,7 @@ mod inner { for i in 0..SIMD_WIDTH { result[i] = self.val[i] > other.val[i]; } - mask32x8 { - val: result, - _marker: PhantomData, - } + mask32x8 { val: result, _marker: PhantomData } } } @@ -206,10 +176,7 @@ mod inner { for i in 0..SIMD_WIDTH { result[i] = self.val[i] & rhs.val[i]; } - Self { - val: result, - _marker: PhantomData, - } + Self { val: result, _marker: PhantomData } } } @@ -221,10 +188,7 @@ mod inner { for i in 0..SIMD_WIDTH { result[i] = self.val[i] | rhs.val[i]; } - Self { - val: result, - _marker: PhantomData, - } + Self { val: result, _marker: PhantomData } } } @@ -236,10 +200,7 @@ mod inner { for i in 0..SIMD_WIDTH { result[i] = self.val[i] ^ rhs.val[i]; } - Self { - val: result, - _marker: PhantomData, - } + Self { val: result, _marker: PhantomData } } } diff --git a/vendor/hayro-jbig2/src/symbol_id_decoder.rs b/vendor/hayro-jbig2/src/symbol_id_decoder.rs index 33ca1c6df..10ee09d6b 100644 --- a/vendor/hayro-jbig2/src/symbol_id_decoder.rs +++ b/vendor/hayro-jbig2/src/symbol_id_decoder.rs @@ -16,10 +16,7 @@ impl SymbolIdDecoder { // than twice the maximum symbol ID." let num_contexts = 1_usize << code_len; - Self { - contexts: vec![ArithmeticDecoderContext::default(); num_contexts], - code_len, - } + Self { contexts: vec![ArithmeticDecoderContext::default(); num_contexts], code_len } } #[inline(always)] From ec93a52260a108e575c31f30e1996b2a78f06ff4 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 08:08:21 +0000 Subject: [PATCH 010/311] Contract stubs: craft-ui-contract --- crates/theme/src/variant.rs | 6 ++ crates/ui-contract/Cargo.toml | 4 +- .../src/contract/collection/events.rs | 5 ++ crates/ui-contract/src/contract/cx/context.rs | 7 ++ crates/ui-contract/src/contract/cx/edit.rs | 1 + crates/ui-contract/src/contract/cx/pointer.rs | 12 +++- crates/ui-contract/src/contract/editor.rs | 44 +++++++++++- crates/ui-contract/src/contract/mod.rs | 3 +- .../ui-contract/src/contract/overlay/place.rs | 23 ++++-- .../ui-contract/src/contract/overlay/props.rs | 3 +- .../ui-contract/src/contract/steps/value.rs | 3 + crates/ui-contract/src/contract/text.rs | 2 +- crates/ui-contract/src/contract/values.rs | 30 ++++++++ crates/ui-contract/src/primitives/draw.rs | 19 ++++- crates/ui-contract/src/primitives/icon.rs | 40 ++++++++++- crates/ui-contract/src/primitives/kit.rs | 27 +++++-- crates/ui-contract/src/primitives/mod.rs | 10 +-- .../src/primitives/pointer_art/art.rs | 6 ++ .../src/primitives/text_adapter.rs | 3 +- .../ui-contract/src/primitives/text_input.rs | 53 +++++++++++++- .../src/primitives/textures/store.rs | 28 ++++++-- .../src/runtime/commands/clipboard.rs | 71 ++++++++++++++++++- .../ui-contract/src/runtime/commands/mod.rs | 2 + crates/ui-contract/src/runtime/egui/access.rs | 8 +++ .../ui-contract/src/runtime/egui/alt_code.rs | 14 ++++ .../ui-contract/src/runtime/egui/clipboard.rs | 48 +++++++++++++ crates/ui-contract/src/runtime/egui/input.rs | 13 ++-- crates/ui-contract/src/runtime/egui/mod.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 7 ++ .../ui-contract/src/runtime/egui/textures.rs | 10 ++- crates/ui-contract/src/runtime/env.rs | 4 +- crates/ui-contract/src/runtime/env/root.rs | 20 +++++- crates/ui-contract/src/runtime/env/shell.rs | 24 +++++++ crates/ui-contract/src/runtime/env/tokens.rs | 15 +++- crates/ui-contract/src/runtime/env/values.rs | 31 ++++++++ crates/ui-contract/src/runtime/ime.rs | 3 + crates/ui-contract/src/runtime/inspect.rs | 39 ++++++++-- crates/ui-contract/src/runtime/install.rs | 10 +++ .../ui-contract/src/runtime/windows/host.rs | 7 ++ crates/ui-contract/src/style/look.rs | 4 +- crates/ui-contract/src/style/span.rs | 10 +++ crates/ui-contract/src/style/surface.rs | 5 +- 42 files changed, 626 insertions(+), 49 deletions(-) create mode 100644 crates/ui-contract/src/runtime/egui/alt_code.rs diff --git a/crates/theme/src/variant.rs b/crates/theme/src/variant.rs index 04c4b7889..345b51761 100644 --- a/crates/theme/src/variant.rs +++ b/crates/theme/src/variant.rs @@ -68,6 +68,12 @@ impl Tone { tokens.color.get(ToneTokens::of(self).soft_fill) } + /// The ink text and icons of the tone read in: `accent.text`, the status foreground, and the normal text for no status. + pub fn ink(self, tokens: &Tokens) -> Rgba { + let _ = tokens; + todo!("ch.C14a") + } + /// The ink text and icons read in on the tone's [`soft_fill`](Self::soft_fill): `accent.on_soft`, the status /// foreground, and the normal text for no status. pub fn on_soft(self, tokens: &Tokens) -> Rgba { diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 112697346..5482f4930 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -45,7 +45,7 @@ craft-window = { workspace = true, features = ["ui"] } # `quit`, which `runtime::windows::logic` routes a root close through. craft-quit = { workspace = true } # `appearance::SystemReader`, the OS appearance the root's `System` choices resolve from. -craft-platform = { workspace = true, features = ["appearance"] } +craft-platform = { workspace = true, features = ["appearance", "clipboard"] } craft-i18n = { workspace = true, features = ["collate"] } log = "0.4" smallvec = { workspace = true } @@ -77,7 +77,7 @@ image = { version = "0.25", default-features = false, features = ["png"], option # The window host's end hook sets `NSWindow.movable` through craft-window's AppKit code. [target.'cfg(target_arch = "wasm32")'.dependencies] # `screen::available`: whether the browser has the EyeDropper, read at install for `Caps::SCREEN_CAPTURE`. -craft-platform = { workspace = true, features = ["screen", "browser"] } +craft-platform = { workspace = true, features = ["screen", "browser", "clipboard"] } [target.'cfg(target_os = "macos")'.dependencies] craft-window = { workspace = true, features = ["ui", "appkit"] } diff --git a/crates/ui-contract/src/contract/collection/events.rs b/crates/ui-contract/src/contract/collection/events.rs index 91cc9d199..b3a415869 100644 --- a/crates/ui-contract/src/contract/collection/events.rs +++ b/crates/ui-contract/src/contract/collection/events.rs @@ -178,6 +178,11 @@ pub enum ColumnEvent { Unsorted, /// The user reset the columns: the app's order, every column shown, the app's widths. The sort stays. Reset, + /// The user pressed the column's remove control. + Removed { + /// The column. + key: ColumnKey, + }, } /// What a collection reports, in drawing order. diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 187ba8fb3..1169f43d2 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -38,6 +38,8 @@ pub(crate) trait TextResult { fn submit_mods(&self) -> craft_keymap::Mods; /// Whether Tab (`Some(true)`) or Shift+Tab (`Some(false)`) moved focus off the part this pass. fn left_by_tab(&self) -> Option; + /// Whether a `TabKey::Reports` part kept focus on Tab (`Some(true)`) or Shift+Tab (`Some(false)`) this pass. + fn tab(&self) -> Option; fn as_any(&self) -> &dyn Any; } @@ -45,6 +47,7 @@ pub(crate) struct RecordedText { pub(crate) outcome: crate::primitives::TextOutcome, pub(crate) submit_mods: craft_keymap::Mods, pub(crate) left_by_tab: Option, + pub(crate) tab: Option, } impl TextResult for RecordedText { @@ -56,6 +59,10 @@ impl TextResult for RecordedText { self.left_by_tab } + fn tab(&self) -> Option { + self.tab + } + fn as_any(&self) -> &dyn Any { self } diff --git a/crates/ui-contract/src/contract/cx/edit.rs b/crates/ui-contract/src/contract/cx/edit.rs index 3f494768a..0d0ed02e7 100644 --- a/crates/ui-contract/src/contract/cx/edit.rs +++ b/crates/ui-contract/src/contract/cx/edit.rs @@ -241,6 +241,7 @@ impl Edit for Cx<'_, C> { response.submitted = self.core.submitted; response.submit_mods = self.core.texts.as_ref().map_or(craft_keymap::Mods::NONE, |(_, text)| text.submit_mods()); response.left_by_tab = self.core.texts.as_ref().and_then(|(_, text)| text.left_by_tab()); + response.tab = self.core.texts.as_ref().and_then(|(_, text)| text.tab()); response.unparsed = self.core.text_invalid; response.value_text = self.core.value_text.borrow().clone(); response.shown = match (&self.shown, self.mixed) { diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index f405877b2..3e27d59a1 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -1,7 +1,7 @@ //! The `Pointer` trait: presses, hover, drags and cursors, on `CxCore` and `Cx`. use super::context::{Activation, Cx, CxCore}; -use crate::contract::Component; +use crate::contract::{Component, Hover}; use crate::primitives::PartResult; use crate::runtime::drag::{self, DragPreview, DropTarget, DropZone, Typed, WindowDropTarget}; use crate::runtime::egui::areas; @@ -28,6 +28,8 @@ pub trait Pointer { fn press(&self) -> &PressState; /// The pointer is over the component's own shapes. fn hit(&self) -> bool; + /// The pointer's stay over the component: over it, entered, left, and clicked while it has stayed over. + fn hover(&self) -> Hover; /// Set only when the component's own shapes won the press and it was released as a click, or /// `Intent::Activate` was routed to it. fn activation(&self) -> Option; @@ -63,6 +65,10 @@ pub trait Pointer { } impl Pointer for CxCore<'_> { + fn hover(&self) -> Hover { + todo!("cv.K45") + } + fn part(&self, part: impl Into) -> &PartResult { let part = part.into(); match self.results.get(&(part.key, part.index)) { @@ -170,6 +176,10 @@ impl CxCore<'_> { } impl Pointer for Cx<'_, C> { + fn hover(&self) -> Hover { + self.core.hover() + } + fn part(&self, part: impl Into) -> &PartResult { self.core.part(part) } diff --git a/crates/ui-contract/src/contract/editor.rs b/crates/ui-contract/src/contract/editor.rs index 7442f513a..60683312d 100644 --- a/crates/ui-contract/src/contract/editor.rs +++ b/crates/ui-contract/src/contract/editor.rs @@ -4,7 +4,7 @@ use super::Component; use super::cx::{Cx, Edit as _, PartsCx}; -use crate::primitives::{EditorPurpose, EditorState, ImeSurface}; +use crate::primitives::{EditorPurpose, EditorState, ImeStamp, ImeSurface}; use crate::runtime::access::text::{self as text_access, Line, Run, TextFacts}; use crate::runtime::egui::{editor as egui_editor, focus as egui_focus}; use crate::runtime::focus::KeyUse; @@ -86,7 +86,49 @@ pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe cx.core.editor_inputs = inputs; } +/// The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a +/// component reports through for the component's editor part. +#[derive(Clone, Debug, PartialEq)] +pub struct EditorHandle { + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + widget: egui::Id, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + rect: Rect, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + purpose: EditorPurpose, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + focused: bool, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + read_only: bool, +} + +impl EditorHandle { + /// Reports the caret and composition to the input-method engine and puts the text facts in the running pass's + /// editor record, which the owning component's report step reads in the same pass. + pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>) { + let _ = (ctx, state); + todo!("cv.K41") + } +} + impl Cx<'_, C> { + /// The editor part of this pass, `None` when the component registered none. + pub fn editor_handle(&self) -> Option { + todo!("cv.K41") + } + + /// Notes the input-method receipt between the stamps `before` and `after` on the egui fork's tracker for this + /// viewport and frame; true when the stamps prove the engine applied it. + pub fn ime_receipt(&self, before: ImeStamp, after: ImeStamp) -> bool { + let _ = (before, after); + todo!("cv.K27") + } + + /// Notes an input-method application change on the egui fork's tracker for this viewport and frame. + pub fn ime_application_change(&self) { + todo!("cv.K27") + } + /// The editor part's inputs of this pass in the order they arrived; call it in `update`. The editor applies them /// to its own document. pub fn editor_input(&mut self) -> impl Iterator + '_ { diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index c756b6d3d..3f40a1ed4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -5,6 +5,7 @@ mod collection; mod container; mod cx; pub(crate) mod editor; +pub use editor::EditorHandle; mod entry; mod faces; pub mod ghost; @@ -100,7 +101,7 @@ pub use registry::{CollectionEntry, ContainerEntry, Exemption, LeafEntry, Patter pub use sampler::{CanvasGesture, Sampler}; pub use settle::SettleCx; pub use text::EDIT_MENU; -pub use values::{Bind, BindMut, EditResponse, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; +pub use values::{Bind, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index ac085d4ec..103afd2fd 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -21,22 +21,35 @@ pub enum Anchor { } /// Where a floating layer sits. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct FloatPlace { - /// A position for the layer's left-top, in the layer's parent space; `None` centres it in the viewport. + /// Where the layer's `corner` sits, in the layer's parent space; `None` centres it in the viewport. pub pos: Option, + /// The corner of the layer that sits at `pos`. + pub corner: Align2, +} + +impl Default for FloatPlace { + fn default() -> Self { + FloatPlace::centred() + } } impl FloatPlace { /// Centred in the viewport. pub const fn centred() -> Self { - FloatPlace { pos: None } + FloatPlace { pos: None, corner: Align2::LEFT_TOP } } - /// At `pos`. + /// With its left-top at `pos`. pub const fn at(pos: Pos2) -> Self { - FloatPlace { pos: Some(pos) } + FloatPlace { pos: Some(pos), corner: Align2::LEFT_TOP } + } + + /// With its `corner` at `pos`. + pub const fn corner_at(pos: Pos2, corner: Align2) -> Self { + FloatPlace { pos: Some(pos), corner } } } diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 5f1f18842..431694fe3 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -189,7 +189,8 @@ impl Overlay { mapped.placed = mapped.placed.map(|rect| to_screen * rect); mapped.placed_at = mapped.placed_at.map(|pos| to_screen * pos); mapped.bounds = mapped.bounds.map(|rect| to_screen * rect); - if let Place::Float(FloatPlace { pos: Some(pos) }) = &mut mapped.place { + // P3(chrome-w7): ch.C20a: the pattern ignores the new `corner`. + if let Place::Float(FloatPlace { pos: Some(pos), .. }) = &mut mapped.place { *pos = to_screen * *pos; } Cow::Owned(mapped) diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index f1a3b1150..9554846a3 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -23,6 +23,9 @@ pub(crate) struct Shown { #[derive(Clone, Default)] pub(crate) struct ShownState { pub last_state: (bool, bool), + /// A pointer click on the control, while the pointer has stayed over it since. + #[allow(dead_code)] // P3(ribbon-w2): cv.K45 + pub clicked_over: bool, pub tweens: Option, } diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index cb5a98056..fd70e9d50 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -512,7 +512,7 @@ pub(crate) fn run( outcome.clicked = out.clicked; // The focus service moved focus off the widget with Tab before this pass's widgets ran. let left_by_tab = if was_focused && !out.focused { crate::runtime::focus::tabbed_off(&ctx, widget) } else { None }; - cx.core.texts = Some((decl.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab }))); + cx.core.texts = Some((decl.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab, tab: None }))); apply_events(cx, resolved.events); cx.core.memory.shown::(state_id).seen = shown_copy(cx); cx.core.submitted |= resolved.submitted; diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index a19e87a01..4f0b9a509 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -436,6 +436,27 @@ pub struct EditResponse { /// The shown value as the component words it to assistive technology ("40.0", "50 %"); `None` for a component /// that gives no such text. pub value_text: Option, + /// A `TabKey::Reports` text part kept focus on Tab (`Some(true)`) or Shift+Tab (`Some(false)`) in this pass; + /// `left_by_tab` stays the fact that focus left by Tab, which such a part never does. + pub tab: Option, + /// The bound caret (byte offset) after the pass. + pub caret: Option, + /// The pointer's stay over the control. + pub hover: Hover, +} + +/// A command-bound control's report of the pointer's stay over it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Hover { + /// The pointer is over the control in this pass. + pub over: bool, + /// The pointer entered the control in this pass. + pub entered: bool, + /// The pointer left the control in this pass. + pub left: bool, + /// The control was clicked with the pointer, which has stayed over it since. + pub clicked: bool, } impl EditResponse { @@ -451,6 +472,9 @@ impl EditResponse { validity, shown: None, value_text: None, + tab: None, + caret: None, + hover: Hover::default(), } } @@ -470,6 +494,9 @@ impl EditResponse { validity: Validity::Ok, shown, value_text: None, + tab: None, + caret: None, + hover: Hover::default(), } } @@ -507,6 +534,9 @@ impl EditResponse { validity, shown, value_text: self.value_text, + tab: self.tab, + caret: self.caret, + hover: self.hover, } } } diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 095991727..5f687bb2f 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -372,7 +372,8 @@ impl<'a> Draw<'a> { } _ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon), } - if let Some(badge) = icon.badge { + // P3(canvas-w3): rb.R18: only the dot paints; the bar's painting comes with its writer. + if let Some(super::IconMark::Dot(badge)) = icon.badge { let radius = self.env.tokens.size.handle.sm / 2.0; let centre = if self.env.direction == Direction::Rtl { square.left_bottom() + Vec2::new(radius, -radius) @@ -491,6 +492,14 @@ impl<'a> Draw<'a> { data_picture(self.painter, self.env.tokens, self.data, texture, rect, uv, CornerRadius::ZERO); } + /// Paints `uv` of `texture` onto the clockwise quad `corners` (from `uv`'s top left), untinted, as data: a + /// disabled component paints it at `Opacity::DISABLED`, and for an inactive part the quad is filled with the + /// theme's disabled fill. A quad has square corners. + pub fn texture_quad(&self, corners: [Pos2; 4], texture: TextureId, uv: Rect) { + let _ = (corners, texture, uv); + todo!("cv.K30") + } + /// Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left. It shows through data, /// so it paints as the data over it: at `Opacity::DISABLED` for a disabled component, and for an inactive part as /// the theme's disabled fill, as `data_fill` does. @@ -604,6 +613,14 @@ pub(super) fn data_picture(painter: &Painter, tokens: &UiTokens, mode: DataMode, } } +/// Paints `uv` of `texture` onto the clockwise quad `corners` as the data in `mode`: untinted through `paint_quad`, +/// or for an inactive part the quad filled with the disabled fill, as `data_picture` fills its rect. +#[allow(dead_code)] // P3(canvas-w3): cv.K30 +pub(super) fn data_quad(painter: &Painter, tokens: &UiTokens, mode: DataMode, texture: TextureId, corners: [Pos2; 4], uv: Rect) { + let _ = (painter, tokens, mode, texture, corners, uv); + todo!("cv.K30") +} + /// Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left, as the data over it in /// `mode`: mapped as `mode` maps a colour, or for an inactive part `rect` in the theme's disabled fill. `Draw::checker` /// and `ContentPainterCx::checker_with` paint through it. diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 017b30e68..7d894dbc4 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -97,8 +97,36 @@ pub struct IconSpec<'a> { pub mirror: Mirror, /// The set an SVG icon is drawn from. pub set: IconSet, - /// A dot of a colour from data at the icon's bottom-trailing corner; see [`badge`](Self::badge). - pub badge: Option, + /// A data-colour mark on the icon: a dot at the bottom-trailing corner (see [`badge`](Self::badge)) or a bar across + /// the bottom (see [`with_mark`](Self::with_mark)). + pub badge: Option, +} + +/// A data-colour mark on an icon. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum IconMark { + /// A dot at the icon's bottom-trailing corner, ringed in the icon's colour. + Dot(DataColor), + /// A bar across the bottom of the icon square, inside it; `weight` is its thickness in points, else `StrokeWidth::Thick`. + Bar { + /// The bar's colour. + color: DataColor, + /// The thickness in points; `None` takes `StrokeWidth::Thick`. + weight: Option, + }, +} + +impl IconMark { + /// A bar of `color` with the default thickness. + pub const fn bar(color: DataColor) -> Self { + IconMark::Bar { color, weight: None } + } + + /// A bar of `color` `weight` points thick. + pub const fn weighted_bar(color: DataColor, weight: f32) -> Self { + IconMark::Bar { color, weight: Some(weight) } + } } impl<'a> IconSpec<'a> { @@ -184,9 +212,15 @@ impl<'a> IconSpec<'a> { /// Adds a dot of `color` at the bottom-trailing corner of an SVG or glyph icon, ringed in the icon's colour: the /// tone a point picker sets. The dot is a data colour (`Draw::data_fill`); the ring follows the icon's colour. pub fn badge(mut self, color: DataColor) -> Self { - self.badge = Some(color); + self.badge = Some(IconMark::Dot(color)); self } + + /// Puts `mark` on the icon in place of any mark it has. + pub fn with_mark(self, mark: IconMark) -> Self { + let _ = mark; + todo!("rb.R18") + } } impl IconSpec<'_> { diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index a20d020f3..089f5b52d 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -344,6 +344,17 @@ const MINOR_SHARE: f32 = 0.45; /// The radius of a dot, in screen points. const DOT_RADIUS: f32 = 0.6; +/// What a grid does when its lines come closer than the minimum step. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum GridCrowding { + /// Draws nothing for an axis whose lines are too close. + #[default] + Hide, + /// Doubles the step, at most 32 times, until the lines fit. + Thin, +} + /// The lines of one axis: positions along it, in the grid's space. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -358,7 +369,8 @@ impl GridAxis { /// The lines of one axis between `lo` and `hi`: majors every `step` from `origin`, minors between them when the /// minor step is at least [`MIN_STEP`] screen points at `zoom`. An axis whose major step is under `MIN_STEP` /// draws nothing; at most [`MAX_LINES`] lines are given. - fn spaced(step: f64, subdivisions: u32, origin: f64, (lo, hi): (f64, f64), zoom: f64) -> GridAxis { + fn spaced(step: f64, subdivisions: u32, origin: f64, (lo, hi): (f64, f64), zoom: f64, crowding: GridCrowding) -> GridAxis { + let _ = crowding; // P3(canvas-w3): cv.K31 if !(step.is_finite() && step > 0.0 && zoom.is_finite() && zoom > 0.0) || step * zoom < MIN_STEP { return GridAxis::default(); } @@ -398,10 +410,17 @@ pub struct GridLines { impl GridLines { /// The lines of a grid in document units: majors every `spacing` from `origin`, `subdivisions` steps to a major /// (1 or 0 is no minor lines), across `extent` as `view` shows it. - pub fn document(view: &CanvasView, extent: kurbo::Rect, spacing: kurbo::Vec2, origin: kurbo::Point, subdivisions: u32) -> Self { + pub fn document( + view: &CanvasView, + extent: kurbo::Rect, + spacing: kurbo::Vec2, + origin: kurbo::Point, + subdivisions: u32, + crowding: GridCrowding, + ) -> Self { let subdivisions = subdivisions.max(1); - let x = GridAxis::spaced(spacing.x, subdivisions, origin.x, (extent.x0, extent.x1), view.zoom_x()); - let y = GridAxis::spaced(spacing.y, subdivisions, origin.y, (extent.y0, extent.y1), view.zoom); + let x = GridAxis::spaced(spacing.x, subdivisions, origin.x, (extent.x0, extent.x1), view.zoom_x(), crowding); + let y = GridAxis::spaced(spacing.y, subdivisions, origin.y, (extent.y0, extent.y1), view.zoom, crowding); let crossings = spacing.x * view.zoom_x() >= CROSSING_MIN && spacing.y * view.zoom >= CROSSING_MIN; GridLines { x, y, extent: Some(extent), crossings, view: Some(*view) } } diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index d302024b4..6510fb055 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -37,11 +37,11 @@ pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; pub(crate) use icon::SvgIcon; -pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; +pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub use ime_surface::ImeSurface; pub use kit::{ - Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse, - fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, + Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, + ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, }; pub use marker::{Marker, MarkerSize}; pub use paint_slot::PaintSlot; @@ -55,7 +55,9 @@ pub(crate) use surface::SurfaceSlot; pub use surround::paint_surround; pub use svg_set::{AppIcons, register_app_icons}; pub use text::{ChordText, HAlign, LayoutRun, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; -pub use text_input::{Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, TextKey, TextOptions}; +pub use text_input::{ + Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, TabKey, TextKey, TextOptions, +}; pub use textures::TextureCache; pub use tool::ToolIcon; diff --git a/crates/ui-contract/src/primitives/pointer_art/art.rs b/crates/ui-contract/src/primitives/pointer_art/art.rs index 6e4a230a4..a739c9eb3 100644 --- a/crates/ui-contract/src/primitives/pointer_art/art.rs +++ b/crates/ui-contract/src/primitives/pointer_art/art.rs @@ -17,6 +17,9 @@ const ARC_HANDLE: f32 = 0.552_284_8; pub(crate) enum Mark { /// A straight line with square-cut ends. Line(Vec2, Vec2, Stroke), + /// A straight line snapped to whole device pixels at the raster scale. + #[allow(dead_code)] // P3(canvas-w3): cv.K29 + Rule(Vec2, Vec2, Stroke), /// A circle's outline. Ring(Vec2, f32, Stroke), /// A rectangle's outline, centred on its edges. @@ -40,6 +43,7 @@ impl Mark { |points: &[Vec2], stroke: &Stroke| Rect::from_points(&points.iter().map(|p| p.to_pos2()).collect::>()).expand(stroke.width / 2.0); match self { Mark::Line(a, b, stroke) => around(&[*a, *b], stroke), + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => Rect::from_center_size(centre.to_pos2(), Vec2::splat(2.0 * radius + stroke.width)), Mark::Frame(rect, stroke) => rect.expand(stroke.width / 2.0), Mark::Disc(centre, radius, _) => Rect::from_center_size(centre.to_pos2(), Vec2::splat(2.0 * radius)), @@ -69,6 +73,7 @@ impl Art { Mark::Line(a, b, stroke) => { painter.line_segment([at + *a, at + *b], *stroke); } + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => { painter.circle_stroke(at + *centre, *radius, *stroke); } @@ -193,6 +198,7 @@ fn rounded_path(rect: Rect, round: f32) -> Option { fn draw(pixmap: &mut tiny_skia::Pixmap, mark: &Mark, transform: tiny_skia::Transform, scale: f32, origin: f32) { match mark { Mark::Line(a, b, stroke) => stroke_path(pixmap, polyline(&[*a, *b], false), *stroke, transform), + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => { stroke_path(pixmap, tiny_skia::PathBuilder::from_circle(centre.x, centre.y, *radius), *stroke, transform) } diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 3217d7577..767d2e603 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -391,7 +391,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut } let separated = input.focused && !input.read_only && state.preedit.is_none() && egui_input::take_separator(ctx, input.options.commit_on); // The part keeps Tab (`keys_of`), so the focus service left it here; it is taken before the widget would insert it. - if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && egui_input::take_tab(ctx) { + // P3(chrome-w6): dg.F20a: `take_tab` gave a bool. + if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && egui_input::take_tab(ctx).is_some() { state.end = Some(End::Rewrite { refuses: true }); } let filter = egui_focus::event_filter(input.keys.keep, false); diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index 178475fe4..68ac811ed 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -34,6 +34,21 @@ impl TextKey { } } +/// What Tab does in a text field. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum TabKey { + /// Tab moves focus. + #[default] + Moves, + /// Tab inserts a tab. + Inserts, + /// Tab and Shift+Tab rewrite the draft (the text part selects it and refuses). + Rewrites, + /// Tab keeps focus and is handed back as `EditResponse::tab`: `Some(true)` for Tab, `Some(false)` for Shift+Tab. + Reports, +} + /// How a text part behaves beyond its codec. #[derive(Clone)] pub struct TextOptions { @@ -57,6 +72,10 @@ pub struct TextOptions { pub ink: Option, /// Tab inserts a tab instead of moving focus. pub tab_inserts: bool, + /// What Tab does in this field; replaces `tab_inserts` and `tab_rewrites`. + pub tab: TabKey, + /// The bound caret as a byte offset, read and written through its binding; the adapter keeps no caret of its own. + pub caret: Option, /// Candidates for the text before the caret. pub complete: Option>, /// Enter accepts the highlighted candidate, as Tab does; off, Enter stays the field's own (a cell commits on it). @@ -112,6 +131,8 @@ impl Default for TextOptions { role: TypeRole::Body, ink: None, tab_inserts: false, + tab: TabKey::default(), + caret: None, complete: None, complete_on_enter: false, replace_selection: None, @@ -272,12 +293,42 @@ pub struct EditorState<'a> { pub can_undo: bool, /// Whether redo has something to do. pub can_redo: bool, + /// The committed text around the caret, or why there is none, with the input-method target's epoch. + pub surrounding: Option<(u64, EditorSurrounding<'a>)>, } +/// The committed window around the caret that an editor reports to the input method, or why there is none. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum EditorSurrounding<'a> { + /// The text around the caret, with UTF-8 offsets of the cursor and the selection anchor into it. + Text { + /// The committed text. + text: &'a str, + /// The cursor's byte offset into `text`. + cursor: usize, + /// The selection anchor's byte offset into `text`. + anchor: usize, + }, + /// The editor has no text to report. + Unavailable { + /// The revision the editor reports it at, if it keeps one. + revision: Option, + }, +} + +pub use egui::ime_context::ImeMutationStamp as ImeStamp; + impl<'a> EditorState<'a> { + /// Reports `s` as the committed text around the caret, for the input-method target at `epoch`. + pub fn surrounding(self, epoch: u64, s: EditorSurrounding<'a>) -> Self { + let _ = (epoch, s); + todo!("cv.K26") + } + /// A state with no selection, no marked text and nothing to undo. pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos) -> Self { - EditorState { caret, lines, caret_at, selection: None, composing: false, can_undo: false, can_redo: false } + EditorState { caret, lines, caret_at, selection: None, composing: false, can_undo: false, can_redo: false, surrounding: None } } } diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index dc768870d..8c0dac632 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -7,7 +7,7 @@ use crate::runtime::egui::pass; use crate::runtime::egui::textures; use craft_behavior::PixelSize; use egui::load::SizedTexture; -use egui::{ColorImage, Context, TextureHandle, TextureId, TextureOptions, Vec2}; +use egui::{ColorImage, Context, Rect, TextureHandle, TextureId, TextureOptions, Vec2}; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::fmt::Debug; @@ -90,6 +90,8 @@ pub struct TextureStoreOptions { /// The sampling of every texture: `TextureOptions::LINEAR` by default; the clipping overlay and pixel-exact /// previews use `TextureOptions::NEAREST`. pub filter: TextureOptions, + /// The largest side of a picture the store puts on shared pages; `None` gives every picture a texture of its own. + pub packed: Option, } impl TextureStoreOptions { @@ -109,7 +111,15 @@ impl TextureStoreOptions { } const fn with_budget(max_bytes: usize, max_entries: usize) -> Self { - Self { budget: TextureBudget::new(max_bytes, max_entries), filter: TextureOptions::LINEAR } + Self { budget: TextureBudget::new(max_bytes, max_entries), filter: TextureOptions::LINEAR, packed: None } + } + + /// Puts pictures up to `max_side` on shared pages written in place; when full, the store recycles the least + /// recently drawn page, never one drawn this pass. A const fn, so it carries the setting without `todo!`. + #[must_use] + pub const fn packed(mut self, max_side: u32) -> Self { + self.packed = Some(max_side); + self } /// The sampling of every texture. @@ -142,9 +152,18 @@ pub struct CachedTexture { pub id: TextureId, /// The texture's size in texels (reduced when the image was past the device limit). pub size: PixelSize, + /// The picture's top-left texel on its page; `[0, 0]` for an unpacked texture. + pub origin: [u32; 2], + /// The size of the page texture the picture sits on; `size` for an unpacked texture. + pub page: PixelSize, } impl CachedTexture { + /// The picture's part of its page texture, in uv coordinates, to paint with `id`. + pub fn uv(&self) -> Rect { + todo!("rb.R20") + } + /// `size` as a vector, for fitting: only the aspect matters to a cell. pub fn size_vec2(&self) -> Vec2 { Vec2::new(self.size.width as f32, self.size.height as f32) @@ -342,7 +361,7 @@ impl TextureStore { } (None, name) => textures::load(ctx, name.unwrap_or_default(), image, filter), }; - let texture = CachedTexture { id: handle.id(), size }; + let texture = CachedTexture { id: handle.id(), size, origin: [0, 0], page: size }; let bytes = byte_size(size); self.with(ctx, |inner| { inner.roll_uploads(frame); @@ -499,7 +518,8 @@ fn texture_size(source: PixelSize, factor: u32) -> PixelSize { } fn cached(handle: &TextureHandle, source: PixelSize, factor: u32) -> CachedTexture { - CachedTexture { id: handle.id(), size: texture_size(source, factor) } + let size = texture_size(source, factor); + CachedTexture { id: handle.id(), size, origin: [0, 0], page: size } } fn picture_bytes(picture: &Picture) -> usize { diff --git a/crates/ui-contract/src/runtime/commands/clipboard.rs b/crates/ui-contract/src/runtime/commands/clipboard.rs index 584253f44..d74cecff2 100644 --- a/crates/ui-contract/src/runtime/commands/clipboard.rs +++ b/crates/ui-contract/src/runtime/commands/clipboard.rs @@ -3,7 +3,9 @@ use crate::runtime::egui::clipboard; use crate::runtime::keys; use crate::runtime::pending::Pending; +use craft_platform::clipboard::{ClipboardError, ClipboardImage, Flavor, Written}; use egui::{ColorImage, Context, Id}; +use std::path::PathBuf; use std::sync::Arc; /// One clipboard item. @@ -16,6 +18,10 @@ pub enum ClipItem { Html(Arc), /// An image. Image(Arc), + /// Rich text. + Rtf(Arc), + /// MathML. + MathMl(Arc), /// An item of an app-defined type. #[non_exhaustive] Custom { @@ -26,6 +32,14 @@ pub enum ClipItem { }, } +impl ClipItem { + /// An item of an app-defined type: `bytes` under the MIME type `mime`. + pub fn custom(mime: impl Into>, bytes: impl Into>) -> ClipItem { + let _ = (mime.into(), bytes.into()); + todo!("pf.C-R3") + } +} + /// What a paste delivers. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -55,6 +69,60 @@ impl ClipboardHandle { ClipboardHandle { ctx: ctx.clone(), slot } } + /// The clipboard handle of `ctx`, over the installed clipboard. + pub fn of(ctx: &Context) -> ClipboardHandle { + let _ = ctx; + todo!("pf.C-R3") + } + + /// Offers `items` in the caller's order, as one offer, and says which flavour the clipboard kept. + pub fn offer(&self, items: &[ClipItem]) -> Result { + let _ = items; + todo!("pf.C-R3") + } + + /// The first of `mimes` the installed clipboard holds. + pub fn read(&self, mimes: &[&str]) -> Result, ClipboardError> { + let _ = mimes; + todo!("pf.C-R3") + } + + /// The clipboard's text. + pub fn read_text(&self) -> Result, ClipboardError> { + todo!("pf.C-R3") + } + + /// The clipboard's image as straight-alpha RGBA8 pixels. + pub fn read_image(&self) -> Result, ClipboardError> { + todo!("pf.C-R3") + } + + /// The files the clipboard holds. + pub fn read_files(&self) -> Result>, ClipboardError> { + todo!("pf.C-R3") + } + + /// Whether the clipboard holds one of `mimes`. + pub fn has(&self, mimes: &[&str]) -> bool { + let _ = mimes; + todo!("pf.C-R3") + } + + /// Whether the clipboard still holds what this app last offered. + pub fn holds_ours(&self) -> bool { + todo!("pf.C-R3") + } + + /// The MIME names of the formats on the clipboard. + pub fn formats(&self) -> Vec { + todo!("pf.C-R3") + } + + /// Whether a late paste offer arrived this frame; true in every pass of that frame. + pub fn arrived(&self) -> bool { + todo!("pf.C-R3") + } + /// Writes every flavour of `items` that the clipboard carries. pub fn put(&self, items: &[ClipItem]) { if !crate::runtime::measure::effect(&self.ctx, "clipboard::put") { @@ -64,7 +132,8 @@ impl ClipboardHandle { match item { ClipItem::Text(text) => clipboard::copy_text(&self.ctx, text.to_string()), ClipItem::Image(image) => clipboard::copy_image(&self.ctx, (**image).clone()), - ClipItem::Html(_) | ClipItem::Custom { .. } => {} + // P3(platform-w3): pf.C-R3: the new items are written through `offer`. + ClipItem::Html(_) | ClipItem::Rtf(_) | ClipItem::MathMl(_) | ClipItem::Custom { .. } => {} } } } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index e7f5ca7af..5bbdc2f30 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -163,6 +163,8 @@ pub enum FireSource { Automation, /// An AccessKit action on a part of a component. Access, + /// A keytip badge, sequence or digit. + Keytip, } /// The phase of the key press that fired a command. diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 8eee24e44..63af4040d 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -48,6 +48,14 @@ fn behind_modal(ctx: &Context, viewport: ViewportId, layer: egui::LayerId) -> bo #[cfg(feature = "testing")] pub type NodeId = accesskit::NodeId; +/// Settles the AccessKit update's focus: when it is not among the update's nodes, focus goes to the tree root. The +/// runtime plugin's output hook calls it once per pass. +#[allow(dead_code)] // P3(chrome-w7): ch.C18 +pub(crate) fn settle_focus(output: &mut egui::FullOutput) { + let _ = output; + todo!("ch.C18") +} + /// The AccessKit id of the node of `id`. #[cfg(feature = "testing")] pub(crate) fn node_id(id: Id) -> NodeId { diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs new file mode 100644 index 000000000..31d50709b --- /dev/null +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -0,0 +1,14 @@ +//! Alt+numpad code entry, folded into the input events in the raw-input step. + +use crate::runtime::env::AltCodePages; + +/// The Alt+numpad entry in progress in one viewport. +#[derive(Default)] +pub(crate) struct AltCodeEntry; + +/// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. +#[allow(dead_code)] // P3(shell-w1): sh.K5 +pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: AltCodePages) { + let _ = (entry, events, pages); + todo!("sh.K5") +} diff --git a/crates/ui-contract/src/runtime/egui/clipboard.rs b/crates/ui-contract/src/runtime/egui/clipboard.rs index e658bec0c..25a762c33 100644 --- a/crates/ui-contract/src/runtime/egui/clipboard.rs +++ b/crates/ui-contract/src/runtime/egui/clipboard.rs @@ -1,6 +1,54 @@ //! Clipboard output commands. +use craft_platform::clipboard::{Clipboard, ClipboardBackend, ClipboardError, ClipboardImage, Flavor}; use egui::{ColorImage, Context}; +use std::path::PathBuf; + +/// The backend the runtime installs when the host gives no clipboard: egui's own copy and paste commands. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) struct EguiClipboard; + +impl ClipboardBackend for EguiClipboard { + fn write(&mut self, flavors: &[Flavor]) -> Result { + let _ = flavors; + todo!("pf.C-R2") + } + + /// egui delivers pasted text only as an input event, so a read finds nothing. + fn read(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + let _ = (mimes, limit); + Ok(None) + } + + fn read_image(&mut self, limit: u64) -> Result, ClipboardError> { + let _ = limit; + todo!("pf.C-R2") + } + + fn read_files(&mut self, limit: usize) -> Result>, ClipboardError> { + let _ = limit; + todo!("pf.C-R2") + } + + fn has(&mut self, mimes: &[&str]) -> bool { + let _ = mimes; + todo!("pf.C-R2") + } +} + +/// Runs `f` on the clipboard installed in `ctx`'s runtime memory. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) fn with(ctx: &Context, f: impl FnOnce(&mut Clipboard) -> R) -> R { + let _ = (ctx, f); + todo!("pf.C-R2") +} + +/// Once per frame, in the pass that receives input: takes a late paste offer for this frame. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) fn begin_frame(ctx: &Context) { + let _ = ctx; + todo!("pf.C-R2") +} /// Puts `text` on the system clipboard. pub(crate) fn copy_text(ctx: &Context, text: String) { diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index c7121511c..a27f21567 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -657,6 +657,9 @@ pub(crate) struct RawState { /// The input time of the last Ctrl+wheel folded into a pinch step. last_pinch: Option, control_click: ControlClick, + /// The Alt+numpad entry in progress. + #[allow(dead_code)] // P3(shell-w1): sh.K5 + alt_code: super::alt_code::AltCodeEntry, } /// The input hook's raw-input step for every viewport, after the injected step joined the input and before the key @@ -690,15 +693,17 @@ pub(crate) fn step_key_pressed(ctx: &Context) -> bool { ctx.input(|input| [Key::ArrowUp, Key::ArrowDown, Key::PageUp, Key::PageDown].into_iter().any(|key| input.key_pressed(key))) } -/// Removes this pass's Tab and Shift+Tab presses from the input events; returns whether there was one. A Tab with -/// Ctrl, Cmd or Alt is the window's, not the field's, and stays. -pub(crate) fn take_tab(ctx: &Context) -> bool { +/// Removes this pass's Tab and Shift+Tab presses from the input events; returns the direction of one if there was +/// one: `Some(true)` for Tab, `Some(false)` for Shift+Tab. A Tab with Ctrl, Cmd or Alt is the window's, not the +/// field's, and stays. +pub(crate) fn take_tab(ctx: &Context) -> Option { ctx.input_mut(|input| { let before = input.events.len(); input.events.retain(|event| { !matches!(event, Event::Key { key: Key::Tab, pressed: true, modifiers, .. } if !modifiers.ctrl && !modifiers.command && !modifiers.mac_cmd && !modifiers.alt) }); - input.events.len() != before + // P3(shell-w1): dg.F20a: the direction is not read yet; every taken press reports Tab. + (input.events.len() != before).then_some(true) }) } diff --git a/crates/ui-contract/src/runtime/egui/mod.rs b/crates/ui-contract/src/runtime/egui/mod.rs index cb380be57..340b21a69 100644 --- a/crates/ui-contract/src/runtime/egui/mod.rs +++ b/crates/ui-contract/src/runtime/egui/mod.rs @@ -2,6 +2,7 @@ pub mod access; pub mod alloc; +pub(crate) mod alt_code; pub mod areas; pub mod child; pub mod clipboard; diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..2af40cc67 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -248,6 +248,13 @@ pub(crate) fn select(ctx: &Context, id: Id, anchor: usize, caret: usize) { state.store(ctx, id); } +/// Whether the widget's field has an undo step and a redo step, as `(undo, redo)`. +#[allow(dead_code)] // P3(chrome-w6): ch.C17a +pub(crate) fn history(ctx: &Context, id: Id) -> (bool, bool) { + let _ = (ctx, id); + todo!("ch.C17a") +} + /// The undo steps of the widget: `Some(text)` when `step` changed it. pub(crate) fn undo(ctx: &Context, id: Id, current: &str, redo: bool) -> Option { let mut state = TextEditState::load(ctx, id)?; diff --git a/crates/ui-contract/src/runtime/egui/textures.rs b/crates/ui-contract/src/runtime/egui/textures.rs index 28ac316fd..ba5477bcf 100644 --- a/crates/ui-contract/src/runtime/egui/textures.rs +++ b/crates/ui-contract/src/runtime/egui/textures.rs @@ -1,6 +1,6 @@ //! Texture uploads and painting: the one place egui's texture calls are made. -use egui::{Color32, ColorImage, Context, CornerRadius, Painter, Rect, TextureHandle, TextureId, TextureOptions}; +use egui::{Color32, ColorImage, Context, CornerRadius, Painter, Pos2, Rect, TextureHandle, TextureId, TextureOptions}; /// Uploads `image` as a texture called `name`, sampled with `filter`. The texture lives as long as the handle. pub(crate) fn load(ctx: &Context, name: String, image: ColorImage, filter: TextureOptions) -> TextureHandle { @@ -17,6 +17,14 @@ pub(crate) fn replace_region(handle: &mut TextureHandle, origin: [u32; 2], image handle.set_partial(origin.map(|n| n as usize), image, filter); } +/// Paints the part `uv` of `texture` onto the clockwise quad `corners` (from `uv`'s top left), tinted by `tint`, as one +/// textured mesh of two triangles. +#[allow(dead_code)] // P3(canvas-w3): cv.K30 +pub(crate) fn paint_quad(painter: &Painter, texture: TextureId, corners: [Pos2; 4], uv: Rect, tint: Color32) { + let _ = (painter, texture, corners, uv, tint); + todo!("cv.K30") +} + /// Paints `texture` in `rect`, the part `uv` of it, tinted by `tint`, with corners rounded by `radius`. #[doc(hidden)] pub fn paint(painter: &Painter, texture: TextureId, rect: Rect, uv: Rect, tint: Color32, radius: CornerRadius) { diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 2809caf04..489a80330 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -8,7 +8,7 @@ mod units; pub use label::{Label, Message, Word}; #[doc(hidden)] pub use shell::ShellEntry; -pub use shell::{BodyMode, RevealEdge, ShellCx, ShellRegions, SlotKey, WindowKey}; +pub use shell::{BodyMode, PageBandRoom, RevealEdge, ShellCx, ShellRegions, SlotKey, WindowKey}; pub use units::{ColumnSize, LengthUnits, PointSize, UnitKind, UnitWords, Units}; use crate::runtime::commands::CommandChain; @@ -51,7 +51,7 @@ pub(crate) use tokens::TokenInputs; #[cfg(feature = "testing")] pub(crate) use tokens::root_token_resolves; use tokens::tokens_for; -pub use values::{ArenaId, ColumnAlign, InBar, MotionPolicy, PaneEdge, RowPressed, Scale}; +pub use values::{AltCodePages, ArenaId, ColumnAlign, InBar, MotionPolicy, PaneEdge, RowPressed, Scale, WheelSpeed}; pub use view::EnvView; /// The inherited context of a `Ui`: one `Arc` clone per read. diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index 56c1837a0..1e1a595fc 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -1,7 +1,7 @@ //! RootEnv, the app's root values each frame, and their resolved form. use super::app_values::AppValues; -use super::values::Scale; +use super::values::{AltCodePages, Scale, WheelSpeed}; use crate::runtime::egui::memory::Service; use crate::runtime::focus::TabReach; use craft_behavior::MotionMode; @@ -51,6 +51,10 @@ pub struct RootEnv { pub values: AppValues, /// Today's date in the host's time zone; the runtime reads no wall clock. pub today: Option, + /// This frame's wheel speed. + pub wheel: WheelSpeed, + /// The code pages that decode Alt+numpad codes. + pub alt_codes: AltCodePages, } impl Default for RootEnv { @@ -72,6 +76,8 @@ impl Default for RootEnv { theme_def: None, values: AppValues::default(), today: None, + wheel: WheelSpeed::default(), + alt_codes: AltCodePages::default(), } } } @@ -197,6 +203,18 @@ impl RootEnv { self.today = Some(date); self } + + /// Sets this frame's wheel speed. + pub fn wheel_speed(self, speed: WheelSpeed) -> Self { + let _ = speed; + todo!("sh.K3") + } + + /// Sets the code pages that decode Alt+numpad codes. + pub fn alt_code_pages(self, pages: AltCodePages) -> Self { + let _ = pages; + todo!("sh.K4") + } } /// The mode, contrast and motion of a pass, with `System` resolved. diff --git a/crates/ui-contract/src/runtime/env/shell.rs b/crates/ui-contract/src/runtime/env/shell.rs index 3e36d5e4a..7e72311d3 100644 --- a/crates/ui-contract/src/runtime/env/shell.rs +++ b/crates/ui-contract/src/runtime/env/shell.rs @@ -125,6 +125,18 @@ struct Inner { region: Option, revealed_rects: RevealedRects, dialog: DialogRecord, + page_band: Option, +} + +/// The room of the page band while a full-window page shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PageBandRoom { + /// The band's rect. + pub rect: Rect, + /// Where the band starts along its axis. + pub start: f32, + /// Where the band ends along its axis. + pub end: f32, } /// The rects that body content registered this pass for the edge it was revealed from. The registry is shared by the @@ -166,6 +178,7 @@ impl ShellCx { region: None, revealed_rects: RevealedRects::default(), dialog: DialogRecord::default(), + page_band: None, }; ShellCx { inner: Arc::new(inner) } } @@ -310,6 +323,17 @@ impl ShellCx { pub fn float_bounds(&self) -> Rect { self.inner.float_bounds } + + /// The page band's room while a full-window page shows, else `None`. + pub fn page_band(&self) -> Option { + todo!("ch.C5a") + } + + /// Sets the page band's room. + pub fn with_page_band(self, room: Option) -> Self { + let _ = room; + todo!("ch.C5a") + } } /// The env entry that carries the shell to its slots and body. A context with no shell holds `None`. diff --git a/crates/ui-contract/src/runtime/env/tokens.rs b/crates/ui-contract/src/runtime/env/tokens.rs index 1c9f71ac1..9a94dd235 100644 --- a/crates/ui-contract/src/runtime/env/tokens.rs +++ b/crates/ui-contract/src/runtime/env/tokens.rs @@ -3,7 +3,7 @@ use super::root::{ResolvedRoot, RootEnv}; use crate::runtime::pass_state; use crate::style::UiTokens; -use craft_theme::{AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins, resolve_sized}; +use craft_theme::{AppId, AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins, resolve_sized}; use egui::Context; use std::sync::Arc; @@ -82,11 +82,15 @@ fn resolve_inputs(inputs: &TokenInputs) -> Arc { Appearance { mode: inputs.mode, contrast: inputs.contrast, size: inputs.density, text_size: inputs.text_size, reduced_motion: false }; let themes = builtins(); if let Some(def) = &inputs.theme_def { - return Arc::new(UiTokens::new(Arc::new(resolve_sized(def, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)); + return Arc::new(UiTokens::new( + Arc::new(resolve_sized(def, appearance, inputs.app.as_ref(), &inputs.sizes).tokens), + inputs.contrast, + inputs.density, + )); } let theme: &ThemeDef = [inputs.theme.as_str(), SUITE_DEFAULT].into_iter().find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)).unwrap_or(&themes[0]); - Arc::new(UiTokens::new(Arc::new(resolve_sized(theme, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)) + Arc::new(UiTokens::new(Arc::new(resolve_sized(theme, appearance, inputs.app.as_ref(), &inputs.sizes).tokens), inputs.contrast, inputs.density)) } /// What the resolved root tokens depend on. The sizes are compared by identity, as `set_input` does. @@ -99,6 +103,8 @@ pub(crate) struct TokenInputs { pub(super) contrast: Contrast, pub(super) density: Size, pub(super) text_size: TextSize, + /// The app whose `[apps.]` theme pins apply over the chosen theme. + pub(super) app: Option, } impl TokenInputs { @@ -111,6 +117,7 @@ impl TokenInputs { contrast: resolved.contrast, density: root.density, text_size: root.text_size, + app: None, // P3(shell-w1): sh.K8 } } @@ -124,6 +131,7 @@ impl TokenInputs { && self.contrast == other.contrast && self.density == other.density && self.text_size == other.text_size + && self.app == other.app } fn same(&self, other: &TokenInputs) -> bool { @@ -134,6 +142,7 @@ impl TokenInputs { && self.contrast == other.contrast && self.density == other.density && self.text_size == other.text_size + && self.app == other.app } } diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 2c61c3e52..dce3947d0 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -24,6 +24,37 @@ impl Default for Scale { } } +/// The user's wheel multipliers: `line` for notches, `point` for touchpad deltas. Distinct from +/// [`WheelScope`](super::WheelScope), which says who takes the wheel, not how far it moves. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WheelSpeed { + /// The multiplier for line (notch) scrolling. + pub line: f32, + /// The multiplier for point (touchpad) scrolling. + pub point: f32, +} + +impl Default for WheelSpeed { + fn default() -> Self { + WheelSpeed { line: 1.0, point: 1.0 } + } +} + +/// Code pages that decode Alt+numpad codes; the app sets them from the system locale. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AltCodePages { + /// The ANSI code page, for codes typed with a leading zero. + pub ansi: u16, + /// The OEM code page, for codes typed without one. + pub oem: u16, +} + +impl Default for AltCodePages { + fn default() -> Self { + AltCodePages { ansi: 1252, oem: 437 } + } +} + /// The motion mode in effect, carried in `Env.motion`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index a9797ec9d..76de8536d 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -18,6 +18,9 @@ struct Engine { queue: Vec, owner: Option, generation: u64, + /// The egui fork's input-method context tracker; replaces `generation`, which stays until canvas-w2 moves its readers. + #[allow(dead_code)] // P3(canvas-w2): cv.K28 + tracker: egui::ime_context::ImeContextTracker, composing: bool, guard: u8, /// A reset was asked for; events of the old composition are dropped until its completion arrives. diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index 18e4138cf..db61675fc 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -8,6 +8,7 @@ use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, measure, pass_state, pointer}; use craft_behavior::PartRef; +use craft_keymap::CommandRef; use egui::{Context, Id, IdMap, IdSet, Rect, Ui}; use std::sync::Arc; @@ -145,6 +146,8 @@ pub struct Element { pub facts: Option, /// Its place in Tab order within the region, from 1, when keyboard focus reaches it. pub stop: Option, + /// The command bound to the control, when it has one. + pub command: Option, } /// A hit area the sensing core registered for a component of the region. @@ -328,7 +331,8 @@ fn finish(ctx: &Context, open: Open) -> Recorded { let Some(owner) = elements.iter().position(|element| element.id == id && element.part.is_none()) else { continue }; let rect = hits.iter().find(|hit| hit.owner == id && hit.part == part).map_or(elements[owner].rect, |hit| hit.rect); let depth = elements[owner].depth + 1; - let element = Element { id, part, component: elements[owner].component, depth, rect, content: rect, facts: None, stop: None }; + let element = + Element { id, part, component: elements[owner].component, depth, rect, content: rect, facts: None, stop: None, command: None }; elements.insert(owner + 1, element); owner + 1 } @@ -381,8 +385,17 @@ pub(crate) fn open_element(ui: &Ui, id: Id, component: &'static str) -> bool { let Some(open) = log.open.last_mut() else { return false }; let component = component.rsplit("::").next().unwrap_or(component); let component = component.split('<').next().unwrap_or(component); - let element = - Element { id, part: None, component, depth: open.stack.len(), rect: Rect::NOTHING, content: Rect::NOTHING, facts: None, stop: None }; + let element = Element { + id, + part: None, + component, + depth: open.stack.len(), + rect: Rect::NOTHING, + content: Rect::NOTHING, + facts: None, + stop: None, + command: None, + }; open.stack.push(open.elements.len()); open.elements.push((element, layer)); true @@ -402,6 +415,14 @@ pub(crate) fn close_element(ctx: &Context, id: Id, rect: Rect, content: Rect) { }); } +/// Notes the command bound to the control `id` in the open region's record; the report step calls it with the +/// component's resolved command. +#[allow(dead_code)] // P3(ribbon-w5): rb.R17 +pub(crate) fn note_command(ctx: &Context, id: Id, command: Option) { + let _ = (ctx, id, command); + todo!("rb.R17") +} + /// Records what the node of the component `id`, or of its part `part` at `rect`, says. pub(crate) fn node_facts(ctx: &Context, id: Id, part: Option, rect: Rect, facts: Facts) { pass_state::with::(ctx, |log| { @@ -412,7 +433,17 @@ pub(crate) fn node_facts(ctx: &Context, id: Id, part: Option, rect: Rec Some(part) => { let (component, depth) = (owner.0.component, owner.0.depth + 1); open.parts.retain(|element| !(element.id == id && element.part == Some(part))); - open.parts.push(Element { id, part: Some(part), component, depth, rect, content: rect, facts: Some(facts), stop: None }); + open.parts.push(Element { + id, + part: Some(part), + component, + depth, + rect, + content: rect, + facts: Some(facts), + stop: None, + command: None, + }); } } }); diff --git a/crates/ui-contract/src/runtime/install.rs b/crates/ui-contract/src/runtime/install.rs index 06ec4dc31..354100a78 100644 --- a/crates/ui-contract/src/runtime/install.rs +++ b/crates/ui-contract/src/runtime/install.rs @@ -42,6 +42,9 @@ pub struct InstallSpec { /// Whether the stories' command sets (`#[command(story)]`) load: the gallery and the story fixtures show /// stories, an app does not, so a story's keys never reach an app's keymap. pub stories: bool, + /// The clipboard the host installs (system, browser event, memory); without one the runtime uses + /// `Clipboard::new(EguiClipboard)`. + pub clipboard: Option, } /// The modifiers the mouse wheel zooms and scrolls sideways with. @@ -82,9 +85,16 @@ impl InstallSpec { app_id: String::new(), pen: None, stories: false, + clipboard: None, } } + /// Installs the host's clipboard (system, browser event, memory) in place of the runtime's own. + pub fn clipboard(self, clipboard: craft_platform::clipboard::Clipboard) -> Self { + let _ = clipboard; + todo!("pf.C-R1") + } + /// Loads the stories' command sets too, for an install that shows stories. pub fn stories(mut self) -> Self { self.stories = true; diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 5ce81ebda..b1de2d369 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -117,6 +117,13 @@ impl WindowHost { screenshot::facts(&self.ctx, viewport) } + /// The viewport's latest settled AccessKit update, a host fact of the window as its screenshot facts are; `None` + /// while AccessKit is off. + pub fn access_tree(&self, viewport: ViewportId) -> Option { + let _ = viewport; + todo!("ch.C19a") + } + /// Queues a pointer move to `at` in `viewport` with `mods` held, delivered on a pass of its own; the modifiers stay /// held after it, and a button held by earlier injected input stays down, so the move drags. With `rest` (seconds) /// the input counts as processed only once the pointer has rested that long. As a window never reports a NaN or diff --git a/crates/ui-contract/src/style/look.rs b/crates/ui-contract/src/style/look.rs index 0bf3dfe9c..176789d4b 100644 --- a/crates/ui-contract/src/style/look.rs +++ b/crates/ui-contract/src/style/look.rs @@ -67,13 +67,15 @@ pub enum SurfaceKind { Scrim, /// An outlined box without fill. Frame, + /// The app's colour as a surface: the strong accent, square corners, no edge. + Brand, } impl SurfaceKind { /// The ink text and icons read on this surface. pub const fn ink(self) -> super::Ink { match self { - SurfaceKind::Scrim => super::Ink::OnDark, + SurfaceKind::Scrim | SurfaceKind::Brand => super::Ink::OnDark, _ => super::Ink::OnPanel, } } diff --git a/crates/ui-contract/src/style/span.rs b/crates/ui-contract/src/style/span.rs index b75ed4afb..7c1151069 100644 --- a/crates/ui-contract/src/style/span.rs +++ b/crates/ui-contract/src/style/span.rs @@ -1,5 +1,6 @@ //! `Span`: one styled stretch of a text run. +use craft_theme::variant::Tone; use std::borrow::Cow; /// One styled stretch of a run. @@ -24,6 +25,8 @@ pub struct Span<'a> { pub underline: bool, /// The role's semibold face, at the role's size. pub strong: bool, + /// Underlined in the ink of this tone. + pub flag: Option, } impl<'a> Span<'a> { @@ -39,9 +42,16 @@ impl<'a> Span<'a> { highlight: false, underline: false, strong: false, + flag: None, } } + /// Underlines the span in the ink of `tone` (spelling `Bad`, grammar `Info`). + pub fn flag(self, tone: Tone) -> Self { + let _ = tone; + todo!("ch.C14a") + } + /// Italic. pub fn italic(mut self) -> Self { self.italic = true; diff --git a/crates/ui-contract/src/style/surface.rs b/crates/ui-contract/src/style/surface.rs index 98c5b6c61..fb9317aed 100644 --- a/crates/ui-contract/src/style/surface.rs +++ b/crates/ui-contract/src/style/surface.rs @@ -115,9 +115,10 @@ pub(crate) fn surface_style(tokens: &UiTokens, kind: SurfaceKind) -> SurfaceStyl K::Knob => c.surface.knob, K::Scrim => c.surface.scrim, K::Frame => Rgba::TRANSPARENT, + K::Brand => c.accent.strong, }; let radius = match kind { - K::Background | K::Canvas | K::Chrome | K::Scrim => 0.0, + K::Background | K::Canvas | K::Chrome | K::Scrim | K::Brand => 0.0, K::Panel | K::Frame => r.panel, K::Raised | K::Pressed | K::Sunken | K::Well | K::Knob => r.control, K::Popup | K::Dialog => r.surface, @@ -132,7 +133,7 @@ pub(crate) fn surface_style(tokens: &UiTokens, kind: SurfaceKind) -> SurfaceStyl let width = StrokeStep::W1.width(1.0); let stroke = |c: Rgba| SurfaceEdge::Border(Stroke::new(width, color(c))); let edge = match (tokens.shape.edge, kind) { - (_, K::Background | K::Canvas | K::Chrome | K::Panel | K::Scrim) => SurfaceEdge::None, + (_, K::Background | K::Canvas | K::Chrome | K::Panel | K::Scrim | K::Brand) => SurfaceEdge::None, (_, K::Popup | K::Dialog | K::Floating | K::Frame) => stroke(c.line.border), (Edge::Flat, K::Raised) => stroke(c.line.border), (Edge::Flat, K::Sunken | K::Pressed | K::Well) => stroke(c.line.control_edge), From 53e525ad786a9ed26cfcbdc0323442ea54cf4b9b Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 08:15:57 +0000 Subject: [PATCH 011/311] Contract stubs: craft-ui-widgets craft-ui-panels --- crates/ui-contract/src/contract/collection.rs | 2 +- .../src/contract/collection/columns.rs | 19 ++++++ crates/ui-contract/src/contract/mod.rs | 14 +++-- crates/ui-contract/src/runtime/overlay.rs | 1 - crates/ui-panels/src/dialog/host.rs | 16 +++++ crates/ui-panels/src/dialog/modal.rs | 18 ++++-- crates/ui-panels/src/dialog/unsaved.rs | 21 ++++++- crates/ui-widgets/src/buttons/button.rs | 15 ++++- crates/ui-widgets/src/buttons/face.rs | 14 +++++ crates/ui-widgets/src/buttons/mod.rs | 20 ++++++- crates/ui-widgets/src/buttons/split_button.rs | 55 ++++++++++++++--- .../ui-widgets/src/buttons/toggle_button.rs | 8 ++- crates/ui-widgets/src/choice/mod.rs | 2 +- crates/ui-widgets/src/choice/segmented.rs | 1 + crates/ui-widgets/src/choice/swatch_table.rs | 15 +++++ crates/ui-widgets/src/display/picture.rs | 13 +++- crates/ui-widgets/src/display/text.rs | 6 ++ crates/ui-widgets/src/menu/bar.rs | 14 +++-- crates/ui-widgets/src/menu/item.rs | 60 ++++++++++++++++--- crates/ui-widgets/src/menu/mod.rs | 2 +- crates/ui-widgets/src/menu/popup.rs | 41 +++++++++++-- crates/ui-widgets/src/menu/search.rs | 8 +-- crates/ui-widgets/src/pickers/combo_box.rs | 40 ++++++++++--- crates/ui-widgets/src/pickers/icon_picker.rs | 21 ++++++- crates/ui-widgets/src/pickers/mod.rs | 6 +- .../ui-widgets/src/pickers/reference_point.rs | 40 ++++++++++--- .../src/pickers/reference_point/stories.rs | 13 ++-- crates/ui-widgets/src/pickers/words.rs | 2 + crates/ui-widgets/src/table/view.rs | 10 +++- crates/ui-widgets/src/tabs/mod.rs | 4 +- crates/ui-widgets/src/tabs/rules.rs | 14 ++++- crates/ui-widgets/src/tabs/strip.rs | 3 + crates/ui-widgets/src/tabs/strip/end.rs | 45 ++++++++++++++ crates/ui-widgets/src/tabs/tab.rs | 15 +++++ crates/ui-widgets/src/text/text_field.rs | 25 ++++++++ 35 files changed, 523 insertions(+), 80 deletions(-) create mode 100644 crates/ui-widgets/src/tabs/strip/end.rs diff --git a/crates/ui-contract/src/contract/collection.rs b/crates/ui-contract/src/contract/collection.rs index d63e89834..754053cdc 100644 --- a/crates/ui-contract/src/contract/collection.rs +++ b/crates/ui-contract/src/contract/collection.rs @@ -6,7 +6,7 @@ mod events; mod props; mod response; -pub use columns::{ColumnAlign, ColumnKind, ColumnLayout, ColumnSort, ColumnSpec, ToggleColumn}; +pub use columns::{ColumnAlign, ColumnKind, ColumnLayout, ColumnRemove, ColumnSort, ColumnSpec, ToggleColumn}; pub use drops::{DropAt, DropKind, DropPayload, DropPlace, EdgePress}; pub use events::{ CollectionEvent, ColumnEvent, ColumnRequest, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit, diff --git a/crates/ui-contract/src/contract/collection/columns.rs b/crates/ui-contract/src/contract/collection/columns.rs index fdf3bd1b8..5e16f1b5a 100644 --- a/crates/ui-contract/src/contract/collection/columns.rs +++ b/crates/ui-contract/src/contract/collection/columns.rs @@ -95,9 +95,27 @@ pub struct ColumnSpec { pub max_share: Option, /// The header menu has a check for the column, so the user can hide it. A column that can't be hidden always shows. pub hideable: bool, + /// A remove control at the header's end, which reports `ColumnEvent::Removed`. + pub remove: Option, +} + +/// The remove control of a column's header. +#[derive(Clone, Debug, PartialEq)] +pub struct ColumnRemove { + /// The control's accessible name. + pub name: Label, + /// Whether the control can be pressed. + pub enabled: bool, } impl ColumnSpec { + /// The column gets a remove control named `name` at its header's end, disabled unless `enabled`. + #[must_use] + pub fn removable(self, name: impl Into