Files
VoelinClient/crates/voelin-ui-vm/src/image.rs
T
faumarayandClaude Sonnet 5.5 ce7ec3afb7 Move the view models into voelin-ui-vm; the Slint models take plain rows
vm/{avatar,tree,servers,streams,home,chat,social,studio} and the UI
settings (settings.rs: keys, UiSettings, LastVoice, ClientPlaybackMap,
the audio form) move into voelin-ui-vm with their tests (102 there now;
the 86 view-model tests of voelin-ui all survive, the old list::sync test
became the list::diff tests). They produce the plain bridge structs, with
Rgb for colours and ImageRef for pictures:

- a file picture is ImageSource::File { path, stamp }: the engine writes
  a picture that arrives again into the same file, so the length and
  write time are part of the reference and a changed file redraws its
  row; size() reads the header once per stamp (no toolkit decoder);
- pictures held in memory (chat previews) are ImageSource::Memory;
- the line cache of the chat no longer keeps Slint models alive for
  pointer equality: plain lines compare by value, so an unchanged
  message makes the same line with or without the cache.

voelin-ui keeps every model as bind::rows::Rows<T>: the plain rows last
shown plus the VecModel, synced with list::diff, converting only the rows
that changed (bind/convert has the From impls). The controllers hand the
view-model rows to Rows::sync and convert forms at the bridge
(`.into()`); crate::vm is now `voelin_ui_vm as vm`, so paths stay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 10:20:55 +03:00

309 lines
10 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::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, 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]>,
},
/// 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 { w, h, .. } => write!(f, "Rgba({w}x{h})"),
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)]
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,
}
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 {
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()
}
}
/// 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.
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::Svg(bytes) => svg_size(bytes),
Self::Memory { bytes, .. } => bytes_size(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 {
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
Size::default()
} else {
Size { width, height }
}
}
/// The size of a picture file's bytes, told by content.
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 {
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))
}
/// 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 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
}
fn svg_size(bytes: &[u8]) -> Size {
let text = String::from_utf8_lossy(bytes);
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
let tag = &text[start..];
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
let stated =
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
let boxed = || {
let mut parts = attribute(tag, "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 a probe of a file found, and what the file was then.
type Probe = (Stamp, Size);
/// 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<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
/// Probes kept at most; the picture cache is far smaller than this.
const MAX_PROBES: usize = 4096;
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
}
#[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);
let pixels = vec![200; width as usize * height as usize * 4];
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.
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
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 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()
);
// 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();
}
}