diff --git a/Cargo.lock b/Cargo.lock index bf6d35f..cd38c6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9764,6 +9764,7 @@ dependencies = [ "image", "miniz_oxide 0.8.9", "png", + "roxmltree", "serde", "serde_json", "unicode-segmentation", diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index 6d903b0..17f3587 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -16,12 +16,15 @@ path = "src/lib.rs" # must show neither. The front ends convert these types (docs/ui.md). [dependencies] chrono = { version = "0.4.45", default-features = false, features = ["clock"] } -# Picture sizes (the header of a file); PNG and JPEG are listed as the -# front end's toolkit used to bring them. +# Whether a picture file decodes, and its size; PNG and JPEG are listed as +# the front end's toolkit used to bring them. image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } serde = { version = "1", features = ["derive"] } # JSON values of the settings and the gateway's configuration keys. serde_json = "1" +# Whether an SVG document is XML with an svg root (the vector renderers read +# it with this parser too). +roxmltree = { version = "0.21", default-features = false, features = ["std"] } # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. diff --git a/crates/voelin-ui-vm/src/image.rs b/crates/voelin-ui-vm/src/image.rs index e92f464..31685ad 100644 --- a/crates/voelin-ui-vm/src/image.rs +++ b/crates/voelin-ui-vm/src/image.rs @@ -4,6 +4,8 @@ use std::collections::HashMap; use std::fmt; +use std::hash::{DefaultHasher, Hasher}; +use std::io::Cursor; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::SystemTime; @@ -28,15 +30,8 @@ pub enum ImageSource { /// What the file was when the reference was made. stamp: Stamp, }, - /// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha. - Rgba { - /// Width in pixels. - w: u32, - /// Height in pixels. - h: u32, - /// `w * h * 4` bytes. - bytes: Arc<[u8]>, - }, + /// Decoded pixels; [`ImageSource::rgba`] makes them. + Rgba(Pixels), /// An SVG document. Svg(Arc<[u8]>), /// A picture file held in memory (a chat picture downloaded for its @@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource { match self { Self::None => f.write_str("None"), Self::File { path, .. } => f.debug_tuple("File").field(path).finish(), - Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"), + Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()), Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()), Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()), } @@ -88,6 +83,39 @@ pub struct Size { pub height: u32, } +/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha. +/// The length always fits the size (`width * height * 4`), so a front end +/// can hand the bytes to its toolkit without checking them. +#[derive(Clone, PartialEq, Eq)] +pub struct Pixels { + w: u32, + h: u32, + bytes: Arc<[u8]>, +} + +impl Pixels { + /// The pixels `bytes` hold, if there are `w * h * 4` of them. + pub fn new(w: u32, h: u32, bytes: impl Into>) -> Option { + let bytes = bytes.into(); + (bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes }) + } + + /// Width in pixels. + pub fn width(&self) -> u32 { + self.w + } + + /// Height in pixels. + pub fn height(&self) -> u32 { + self.h + } + + /// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row. + pub fn bytes(&self) -> &[u8] { + &self.bytes + } +} + impl ImageSource { /// A reference to no picture. pub fn none() -> ImageRef { @@ -104,27 +132,24 @@ impl ImageSource { /// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue, /// alpha); no picture if the length does not fit. pub fn rgba(w: u32, h: u32, bytes: impl Into>) -> ImageRef { - let bytes = bytes.into(); - if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 { - Arc::new(Self::Rgba { w, h, bytes }) - } else { - Self::none() - } + Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels))) } /// The size the picture shows with; 0 by 0 when there is none or it can - /// not be shown: a file that is missing, is not a picture, or is too - /// large to decode (a front end drops those, as it would show nothing). - /// A file's size is read from its header, once while it stays as it is; - /// a vector picture has none of its own: its stated width and height, - /// else 1 by 1. + /// not be shown: a file that is missing, does not decode, or is too large + /// to decode (a front end drops those, as it would show nothing). So a + /// picture that has a size shows: a raster picture is decoded to tell + /// (its first frame, as a front end would show it), an SVG document must + /// parse. A file or a downloaded picture is checked once while it stays + /// as it is; a vector picture has no size of its own: its stated width + /// and height, else 1 by 1. pub fn size(&self) -> Size { match self { Self::None => Size::default(), Self::File { path, stamp } => file_size(path, *stamp), - Self::Rgba { w, h, .. } => Size { width: *w, height: *h }, + Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() }, Self::Svg(bytes) => svg_size(bytes), - Self::Memory { bytes, .. } => bytes_size(bytes), + Self::Memory { key, bytes } => memory_size(key, bytes), } } @@ -138,24 +163,38 @@ impl ImageSource { const MAX_DECODED_BYTES: u64 = 128 << 20; fn checked(width: u32, height: u32) -> Size { - if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES { + let bytes = u128::from(width) * u128::from(height) * 4; + if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) { Size::default() } else { Size { width, height } } } -/// The size of a picture file's bytes, told by content. +/// What a picture file's bytes show as, told by content: a raster picture is +/// decoded (its first frame; the size comes from the header, the decoding +/// tells whether the rest of the file is a picture too), an SVG document +/// must parse. Anything else, or anything that does not decode, shows +/// nothing. fn bytes_size(bytes: &[u8]) -> Size { let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes); - let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format() - else { + let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return Size::default(); }; if reader.format().is_none() { return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() }; } - reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h)) + // What a front end allows itself: 16 bits a channel take twice the bytes. + let mut limits = image::Limits::default(); + limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20)); + reader.limits(limits); + let Ok(decoder) = reader.into_decoder() else { return Size::default() }; + let (width, height) = image::ImageDecoder::dimensions(&decoder); + let size = checked(width, height); + if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() { + return Size::default(); + } + size } /// The number at the start of an attribute's value ("48", "48px", "4.5em"). @@ -164,34 +203,25 @@ fn number(value: &str) -> Option { value[..end].parse::().ok().filter(|v| *v >= 1.0).map(|v| v as u32) } -/// The value of `name="…"` in the root tag of an SVG. -fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { - let mut rest = tag; - while let Some(at) = rest.find(name) { - let before = rest[..at].chars().next_back(); - let after = &rest[at + name.len()..]; - let after = after.trim_start(); - if before.is_none_or(char::is_whitespace) - && let Some(value) = after.strip_prefix('=') - { - let value = value.trim_start(); - let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?; - return value[1..].split(quote).next(); - } - rest = &rest[at + name.len()..]; - } - None -} - +/// The size of an SVG document: none unless it is XML (as the vector +/// renderers read it, a doctype allowed) whose root is an `svg` element. fn svg_size(bytes: &[u8]) -> Size { - let text = String::from_utf8_lossy(bytes); - let Some(start) = text.find("').unwrap_or(tag.len())]; + const NAMESPACE: &str = "http://www.w3.org/2000/svg"; + let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes); + let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() }; + let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }; + let Ok(document) = roxmltree::Document::parse_with_options(text, options) else { + return Size::default(); + }; + let root = document.root_element(); + let name = root.tag_name(); + if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) { + return Size::default(); + } let stated = - attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number)); + root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number)); let boxed = || { - let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty()); + let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty()); let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?); number(w).zip(number(h)) }; @@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size { checked(width, height) } -/// What a probe of a file found, and what the file was then. -type Probe = (Stamp, Size); +/// What identifies the bytes a probe looked at. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Seen { + /// A file as it was (length and time). + File(Stamp), + /// A picture in memory: its length and a hash of its bytes. + Bytes(usize, u64), +} -/// Probed files, so a picture shown in many rows is read once; entries are -/// checked against the file's length and time before use. -static PROBES: Mutex>> = Mutex::new(None); +/// Where a probed picture is. +#[derive(Clone, PartialEq, Eq, Hash)] +enum Probed { + File(PathBuf), + Memory(Arc), +} + +/// Probed pictures with what they were then, so a picture shown in many +/// rows is decoded once; an entry is checked against the picture's length +/// and time (or bytes) before use. +static PROBES: Mutex>> = Mutex::new(None); /// Probes kept at most; the picture cache is far smaller than this. const MAX_PROBES: usize = 4096; +/// The size of the picture at `at`, from the cache when it is still the +/// same, else from `probe` (run without the lock: it decodes). +fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size { + { + let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at)) + && *was == seen + { + return *size; + } + } + let size = probe(); + let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); + let probes = guard.get_or_insert_with(HashMap::new); + if probes.len() >= MAX_PROBES { + probes.clear(); + } + probes.insert(at, (seen, size)); + size +} + fn file_size(path: &Path, stamp: Stamp) -> Size { if stamp == Stamp::default() { return Size::default(); } - let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); - let probes = guard.get_or_insert_with(HashMap::new); - if let Some((was, size)) = probes.get(path) - && *was == stamp - { - return *size; - } - // The file is read with the lock held; probes are short and rare. - let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes)); - if probes.len() >= MAX_PROBES { - probes.clear(); - } - probes.insert(path.to_owned(), (stamp, size)); - size + probed(Probed::File(path.to_owned()), Seen::File(stamp), || { + std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes)) + }) +} + +fn memory_size(key: &Arc, bytes: &[u8]) -> Size { + let mut hasher = DefaultHasher::new(); + hasher.write(bytes); + probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || { + bytes_size(bytes) + }) } #[cfg(test)] @@ -239,7 +301,15 @@ mod tests { let mut encoder = ::png::Encoder::new(&mut bytes, width, height); encoder.set_color(::png::ColorType::Rgba); encoder.set_depth(::png::BitDepth::Eight); - let pixels = vec![200; width as usize * height as usize * 4]; + // Pixels that do not compress to nothing, so cutting the file short + // cuts into the picture. + let mut seed = 0x2545_f491_u32; + let pixels: Vec = (0..width as usize * height as usize * 4) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 24) as u8 + }) + .collect(); encoder.write_header().unwrap().write_image_data(&pixels).unwrap(); bytes } @@ -257,8 +327,13 @@ mod tests { let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]); assert_eq!(pixels.size(), Size { width: 2, height: 3 }); assert!(!pixels.is_empty()); - // The wrong length is no picture. + // The wrong length is no picture, and no pixels either. assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty()); + assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty()); + assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none()); + assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none()); + let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") }; + assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24)); assert_eq!(format!("{pixels:?}"), "Rgba(2x3)"); } @@ -284,6 +359,48 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_file_that_does_not_decode_shows_nothing() { + let dir = temp("corrupt"); + let whole = png(32, 32); + // The header is fine, the picture is cut short (a download that + // stopped, a cache file written halfway). + let cut = dir.join("cut"); + std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap(); + assert!(ImageSource::file(&cut).is_empty()); + // The header is fine, the data is not: flipped bytes in the image + // data, from the middle of the file to its end. + let mut flipped = whole.clone(); + let from = flipped.len() / 2; + for byte in &mut flipped[from..] { + *byte = !*byte; + } + let garbled = dir.join("garbled"); + std::fs::write(&garbled, &flipped).unwrap(); + assert!(ImageSource::file(&garbled).is_empty()); + // The whole file shows, and the answer is kept while it stays so. + let good = dir.join("good"); + std::fs::write(&good, &whole).unwrap(); + assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 }); + // A file that is made whole shows (another stamp: another answer). + std::fs::write(&cut, &whole).unwrap(); + assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 }); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_downloaded_picture_is_checked_too() { + let whole = png(16, 16); + let memory = + |key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() }; + assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 }); + assert!(memory("cut", &whole[..whole.len() / 2]).is_empty()); + // The same key with other bytes is another picture. + assert!(memory("same", &whole[..whole.len() / 2]).is_empty()); + assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 }); + assert!(memory("none", b"").is_empty()); + } + #[test] fn vector_pictures() { let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size(); @@ -296,6 +413,24 @@ mod tests { ImageSource::Svg(b"".as_slice().into()) .is_empty() ); + // Not an SVG document: cut off, a sibling of the root, other roots, + // not text. + assert!(size("").width == 0); + assert!(size("").width == 0); + assert!(size("").width == 0); + assert!(size("").width == 0); + assert_eq!( + size("").height, + 9 + ); + assert!( + ImageSource::Svg(b"\xff".as_slice().into()).is_empty() + ); + // A doctype, as editors write it. + let doctype = ""; + assert_eq!(size(doctype), Size { width: 5, height: 6 }); // An SVG file with a byte order mark and a prolog, and in memory. let svg: &[u8] = b"\xef\xbb\xbf"; let dir = temp("svg"); diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index fa25c8f..66e5969 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -23,4 +23,4 @@ pub mod studio_bridge; pub mod tree; pub use color::Rgb; -pub use image::{ImageRef, ImageSource, Size}; +pub use image::{ImageRef, ImageSource, Pixels, Size}; diff --git a/crates/voelin-ui/src/bind/convert.rs b/crates/voelin-ui/src/bind/convert.rs index 3cddcbb..61cfd84 100644 --- a/crates/voelin-ui/src/bind/convert.rs +++ b/crates/voelin-ui/src/bind/convert.rs @@ -37,8 +37,14 @@ pub(crate) fn image(picture: &ImageRef) -> Image { match &**picture { ImageSource::None => Image::default(), ImageSource::File { path, .. } => crate::images::file(path), - ImageSource::Rgba { w, h, bytes } => { - Image::from_rgba8(SharedPixelBuffer::::clone_from_slice(bytes, *w, *h)) + // `Pixels` holds `width * height * 4` bytes, which `clone_from_slice` + // needs (it panics otherwise). + ImageSource::Rgba(pixels) => { + Image::from_rgba8(SharedPixelBuffer::::clone_from_slice( + pixels.bytes(), + pixels.width(), + pixels.height(), + )) } ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(), ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes),