Files
VoelinClient/crates/voelin-ui-vm/src/image.rs
T
faumarayandClaude Sonnet 5.5 a2b064bb57 voelin-ui-vm: what the channel tree and the members need of both front ends
The GPUI tree and members pane (the next commits) call these; the Slint
front end keeps its own copies of two of them, since voelin-ui is not
edited in this round (docs/ui.md says which).

- tree::member_card: the card over a member row, built from the session,
  the contacts and the local playback (the Slint members.rs builds the
  same inline).
- servers::sequence::join_channel, join_with_password and connect_into:
  a double-click in the tree, the password dialog's Join, and the connect
  into a channel of a server with no voice (the Slint bind/servers.rs
  has the same three, over logic::join_channel).
- servers::logic::open_member: the card of a client opens or closes.
- settings::UI_TREE (ui.tree), TreeState: the channels each server's tree
  has folded shut and the channel selected, by bookmark id. Like ui.window
  it is the GPUI front end's own key; Slint's tree forgets both at exit.
- image::Stamp is Hash, so a front end can key a decoded picture by the
  file and the stamp it had.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 23:30:59 +03:00

444 lines
16 KiB
Rust

//! Pictures without a toolkit: where a picture comes from, and how large it
//! is. A front end turns an [`ImageRef`] into its own image type (Slint's
//! `Image` through its decoded-picture cache, GPUI's `img()`).
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;
/// A picture: shared, cheap to clone, compared by what it is made of.
pub type ImageRef = Arc<ImageSource>;
/// Where a picture comes from.
#[derive(Clone, Default, PartialEq, Eq)]
pub enum ImageSource {
/// No picture.
#[default]
None,
/// A file of the engine's picture cache (`avatars/<md5>`, `icons/<id>`,
/// banners): PNG, JPEG, GIF, WebP, BMP, ICO or SVG, told by content, not
/// by name. The engine writes a picture that arrives again into the same
/// file, so the reference carries the file's [`Stamp`]: a changed file is
/// another picture, and a list that shows it redraws the row.
File {
/// Where the file is.
path: PathBuf,
/// What the file was when the reference was made.
stamp: Stamp,
},
/// 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
/// preview): the file's bytes, and a key the front end may keep its
/// decoded picture under.
Memory {
/// Names the picture, for caches.
key: Arc<str>,
/// The file's bytes.
bytes: Arc<[u8]>,
},
}
impl fmt::Debug for ImageSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => f.write_str("None"),
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
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()),
}
}
}
/// What identifies a file's content without reading it: its length and the
/// time it was last written. Both zero for a file that is missing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Stamp {
len: u64,
modified: Option<SystemTime>,
}
impl Stamp {
/// The stamp of the file at `path`.
pub fn of(path: &Path) -> Self {
std::fs::metadata(path)
.map(|meta| Self { len: meta.len(), modified: meta.modified().ok() })
.unwrap_or_default()
}
}
/// A picture's size in pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Size {
/// Width, 0 for no picture.
pub width: u32,
/// Height, 0 for no picture.
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<Arc<[u8]>>) -> Option<Self> {
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 {
ImageRef::default()
}
/// A reference to a file of the picture cache, as the file is now.
pub fn file(path: impl Into<PathBuf>) -> ImageRef {
let path = path.into();
let stamp = Stamp::of(&path);
Arc::new(Self::File { path, stamp })
}
/// 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<Arc<[u8]>>) -> ImageRef {
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, 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(pixels) => Size { width: pixels.width(), height: pixels.height() },
Self::Svg(bytes) => svg_size(bytes),
Self::Memory { key, bytes } => memory_size(key, bytes),
}
}
/// There is no picture, or it can not be shown ([`Self::size`]).
pub fn is_empty(&self) -> bool {
self.size().width == 0
}
}
/// A picture with more pixels than this (as RGBA bytes) is not decoded.
const MAX_DECODED_BYTES: u64 = 128 << 20;
fn checked(width: u32, height: u32) -> Size {
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 }
}
}
/// 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(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() };
}
// 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").
fn number(value: &str) -> Option<u32> {
let end = value.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(value.len());
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
}
/// 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 {
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 =
root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number));
let boxed = || {
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))
};
let (width, height) = stated.or_else(boxed).unwrap_or((1, 1));
checked(width, height)
}
/// 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),
}
/// Where a probed picture is.
#[derive(Clone, PartialEq, Eq, Hash)]
enum Probed {
File(PathBuf),
Memory(Arc<str>),
}
/// 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<Option<HashMap<Probed, (Seen, Size)>>> = 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();
}
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<str>, 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)]
mod tests {
use super::*;
/// A PNG of `width` by `height` pixels.
pub(crate) fn png(width: u32, height: u32) -> Vec<u8> {
let mut bytes = Vec::new();
let mut encoder = ::png::Encoder::new(&mut bytes, width, height);
encoder.set_color(::png::ColorType::Rgba);
encoder.set_depth(::png::BitDepth::Eight);
// 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<u8> = (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
}
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-ui-vm-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn pixels_and_nothing() {
assert_eq!(ImageSource::none().size(), Size::default());
assert!(ImageSource::none().is_empty());
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, 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)");
}
#[test]
fn files_by_content() {
let dir = temp("files");
// No extension: the cache's files have none.
let path = dir.join("1234");
std::fs::write(&path, png(4, 2)).unwrap();
assert_eq!(ImageSource::file(&path).size(), Size { width: 4, height: 2 });
let before = ImageSource::file(&path);
// A changed file is read again.
std::fs::write(&path, png(5, 3)).unwrap();
let after = ImageSource::file(&path);
assert_eq!(after.size(), Size { width: 5, height: 3 });
// The same file, another picture: a list redraws the row.
assert_ne!(before, after);
assert_eq!(after, ImageSource::file(&path));
let junk = dir.join("junk");
std::fs::write(&junk, b"not a picture").unwrap();
assert!(ImageSource::file(&junk).is_empty());
assert!(ImageSource::file(dir.join("missing")).is_empty());
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();
assert_eq!(size("<svg width=\"32\" height=\"16\"/>"), Size { width: 32, height: 16 });
assert_eq!(size("<svg viewBox='0 0 24 12'/>"), Size { width: 24, height: 12 });
assert_eq!(size("<svg xmlns='http://www.w3.org/2000/svg'/>"), Size { width: 1, height: 1 });
assert_eq!(size("<svg width=\"4096px\" height=\"4096px\"/>").width, 4096);
// Too large to decode.
assert!(
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
.is_empty()
);
// Not an SVG document: cut off, a sibling of the root, other roots,
// not text.
assert!(size("<svg width=\"8\" height=\"8\"").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"><g>").width == 0);
assert!(size("<svg width=\"8\" height=\"8\"/><svg/>").width == 0);
assert!(size("<html width=\"8\" height=\"8\"/>").width == 0);
assert!(size("<svg xmlns='urn:other' width='8' height='8'/>").width == 0);
assert_eq!(
size("<svg xmlns='http://www.w3.org/2000/svg' width='8' height='9'/>").height,
9
);
assert!(
ImageSource::Svg(b"<svg width='8' height='8'>\xff</svg>".as_slice().into()).is_empty()
);
// A doctype, as editors write it.
let doctype = "<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \
\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"5\" height=\"6\"/>";
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<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
let dir = temp("svg");
std::fs::write(dir.join("icon"), svg).unwrap();
assert_eq!(ImageSource::file(dir.join("icon")).size().width, 8);
let memory = ImageSource::Memory { key: "k".into(), bytes: png(3, 3).into() };
assert_eq!(memory.size(), Size { width: 3, height: 3 });
std::fs::remove_dir_all(dir).unwrap();
}
}