app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
[package]
name = "rune-image"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Content-addressed image decoding, linear-light mip generation, shelf pixel atlas, SVG/AVIF codecs, and OS app icon rasterization for Rune."
[features]
default = ["svg"]
# SVG and SVGZ images (`ImageCache::svg`, `file`, `load_mime`, and `load` on sniffed SVG bytes),
# and scalable Linux app icons, rasterized by resvg. Off, those images resolve to `Image::error`.
svg = ["dep:resvg"]
# AVIF images (`ImageCache::load` on AVIF bytes), decoded natively by rav1d, a Rust port of
# dav1d; an animated AVIF shows its first frame. Building it for x86 needs NASM on the PATH for
# rav1d's assembly. Off, AVIF bytes resolve to `Image::error`. No effect on web, where the
# browser decodes AVIF.
avif = ["dep:avif-decode"]
[dependencies]
blake3 = { workspace = true }
image = { workspace = true, features = ["png"] }
resvg = { workspace = true, optional = true }
rune-core = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
avif-decode = { version = "3", optional = true }
# JPEG, GIF, WebP, BMP and ICO decoding; a web build hands them to the browser's codecs instead.
image = { workspace = true, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = { workspace = true }
objc2-foundation = { workspace = true, features = ["std", "NSGeometry", "NSObject", "NSString", "objc2-core-foundation"] }
[target.'cfg(target_os = "macos")'.dev-dependencies]
png = { workspace = true }
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { workspace = true }
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
[lints]
workspace = true
+140
View File
@@ -0,0 +1,140 @@
//! Animated GIF, WebP and PNG (APNG): every frame composited onto the canvas and given a mip
//! chain on the cache worker, with the time each one ends. A paint picks the frame for its
//! clock (`Motion::at`) and wakes for the next only while the image is drawn, so an animation
//! off screen or in a hidden window costs nothing.
use std::io::Cursor;
use image::{AnimationDecoder, ImageDecoder};
use super::{Decoded, ImageError, Mip, mip_chain};
/// Decoded pixels the frames of one animation may take, mips included; a larger one shows its
/// first frame still.
const BUDGET: usize = 256 << 20;
/// The frames after the first (which is [`Decoded::mips`]) and when each frame ends.
pub(crate) struct Motion {
/// Frames 1.. as mip chains.
pub frames: Vec<Vec<Mip>>,
/// Seconds from the start of a play to the end of each frame, frame 0's first; the last is
/// the length of a play.
pub ends: Vec<f64>,
/// How many times it plays; `None` loops forever.
pub plays: Option<u32>,
}
impl Motion {
/// The frame `t` seconds after the animation started, and when (on the same clock) the
/// next one shows; `None` once its last play has ended and it rests on its last frame.
pub(crate) fn at(&self, t: f64) -> (usize, Option<f64>) {
let last = self.ends.len() - 1;
let period = self.ends[last];
let play = (t.max(0.0) / period).floor();
if self.plays.is_some_and(|n| play >= f64::from(n)) { return (last, None); }
let within = t.max(0.0) - play * period;
let i = self.ends.partition_point(|&end| end <= within).min(last);
(i, Some(play * period + self.ends[i]))
}
/// Frame `i`'s mips, given frame 0's.
pub(crate) fn frame<'a>(&'a self, first: &'a [Mip], i: usize) -> &'a [Mip] {
if i == 0 { first } else { &self.frames[i - 1] }
}
}
/// Which animated format `bytes` sniff as. A web build hands GIF and WebP to the browser,
/// which decodes their first frame.
#[derive(Clone, Copy)]
enum Kind {
#[cfg(not(target_arch = "wasm32"))]
Gif,
#[cfg(not(target_arch = "wasm32"))]
WebP,
Png,
}
fn sniff(bytes: &[u8]) -> Option<Kind> {
#[cfg(not(target_arch = "wasm32"))]
if bytes.starts_with(b"GIF8") { return Some(Kind::Gif); }
#[cfg(not(target_arch = "wasm32"))]
if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { return Some(Kind::WebP); }
bytes.starts_with(b"\x89PNG\r\n\x1a\n").then_some(Kind::Png)
}
/// An animation of more than one frame, or `None` for a still (or a format that isn't
/// animated), which decodes as any image does.
pub(super) fn decode(bytes: &[u8]) -> Option<Result<Decoded, ImageError>> {
let kind = sniff(bytes)?;
let error = |e: image::ImageError| ImageError(e.to_string());
let cursor = Cursor::new(bytes);
// Each format's own loop count: a GIF's says how often it repeats after its first play, a
// WebP's and an APNG's how often it plays (as browsers count them).
let (size, frames, plays) = match kind {
#[cfg(not(target_arch = "wasm32"))]
Kind::Gif => {
let decoder = image::codecs::gif::GifDecoder::new(cursor).ok()?;
let plays = finite(decoder.loop_count()).map(|n| n.saturating_add(1));
(decoder.dimensions(), decoder.into_frames(), plays)
}
#[cfg(not(target_arch = "wasm32"))]
Kind::WebP => {
let mut decoder = image::codecs::webp::WebPDecoder::new(cursor).ok()?;
if !decoder.has_animation() { return None; }
// Browsers composite on transparency, whatever background the file names.
decoder.set_background_color(image::Rgba([0, 0, 0, 0])).ok()?;
let plays = finite(decoder.loop_count());
(decoder.dimensions(), decoder.into_frames(), plays)
}
Kind::Png => {
let decoder = image::codecs::png::PngDecoder::new(cursor).ok()?;
if !decoder.is_apng().ok()? { return None; }
let size = decoder.dimensions();
let decoder = decoder.apng().ok()?;
let plays = finite(decoder.loop_count());
(size, decoder.into_frames(), plays)
}
};
let (w, h) = size;
if w == 0 || h == 0 || w > 8192 || h > 8192 { return Some(Err(ImageError("animation is too large".into()))); }
let per_frame = w as usize * h as usize * 16 / 3;
let mut chains = Vec::new();
let mut ends = Vec::new();
let mut elapsed = 0.0;
for frame in frames {
let frame = match frame {
Ok(frame) => frame,
// A truncated file plays the frames it has, as browsers do.
Err(_) if !chains.is_empty() => break,
Err(e) => return Some(Err(error(e))),
};
if !chains.is_empty() && (chains.len() + 1) * per_frame > BUDGET { return Some(still(chains)); }
let (numer, denom) = frame.delay().numer_denom_ms();
let ms = f64::from(numer) / f64::from(denom.max(1));
// Browsers show a frame of 10 ms or less for 100 ms: such files mean "as fast as you
// can", which would otherwise spin.
elapsed += if ms <= 10.0 { 0.1 } else { ms / 1000.0 };
let buffer = frame.into_buffer();
match mip_chain(buffer.width(), buffer.height(), buffer.as_raw()) {
Ok(decoded) => chains.push(decoded.mips),
Err(e) => return Some(Err(e)),
}
ends.push(elapsed);
}
if chains.len() < 2 { return (!chains.is_empty()).then(|| still(chains)); }
let mut chains = chains.into_iter();
let first = chains.next().expect("two frames or more");
Some(Ok(Decoded { mips: first, motion: Some(Box::new(Motion { frames: chains.collect(), ends, plays })) }))
}
/// The first frame alone, for an animation too large to hold.
fn still(chains: Vec<Vec<Mip>>) -> Result<Decoded, ImageError> {
let first = chains.into_iter().next().ok_or_else(|| ImageError("animation has no frames".into()))?;
Ok(Decoded { mips: first, motion: None })
}
fn finite(count: image::metadata::LoopCount) -> Option<u32> {
match count {
image::metadata::LoopCount::Infinite => None,
image::metadata::LoopCount::Finite(n) => Some(n.get()),
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Platform app-bundle and file icon rasterization (`app_icon_rgba`).
#![allow(unsafe_code)]
use super::ImageError;
#[cfg(target_os = "macos")]
#[link(name = "AppKit", kind = "framework")]
unsafe extern "C" {}
/// Rasterize the platform icon for an app bundle or file at about `px`×`px`, as straight-alpha
/// sRGB RGBA8 ready for [`ImageCache::rgba`](super::ImageCache::rgba). Most code wants
/// [`ImageCache::app_icon`](super::ImageCache::app_icon), which calls this on its worker and
/// caches the result.
///
/// macOS: `NSWorkspace iconForFile:` drawn into a thread-local `NSBitmapImageRep` context.
/// Neither needs the main thread: `NSWorkspace` is not main-actor isolated in the SDK, and
/// AppKit allows drawing an `NSImage` into a bitmap context owned by a secondary thread.
/// Windows: the file's first icon from `PrivateExtractIconsW` at `px` (at most 256).
/// Linux: the closest theme size at or above `px`, or an SVG rasterized to fit `px`; a
/// non-square pixmap keeps its aspect ratio.
pub fn app_icon_rgba(path: &std::path::Path, px: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
if px == 0 || px > 1024 { return Err(ImageError("app icon size must be 1..=1024 pixels".into())); }
#[cfg(target_os = "macos")]
{ macos_icon(path, px) }
#[cfg(target_os = "windows")]
{ windows_icon(path, px) }
#[cfg(target_os = "linux")]
{ linux_icon(path, px) }
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
{ let _ = path; Err(ImageError("app_icon is unsupported on this platform".into())) }
}
#[cfg(target_os = "windows")]
fn windows_icon(path: &std::path::Path, px: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Graphics::Gdi::{
BI_RGB, BITMAP, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleDC, DIB_RGB_COLORS, DeleteDC, DeleteObject, GetDIBits, GetObjectW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON, ICONINFO, PrivateExtractIconsW};
let err = |what: &str| ImageError(format!("{what}: {}", path.display()));
// PrivateExtractIconsW reads a fixed MAX_PATH buffer.
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
if wide.len() > 260 { return Err(err("icon path is longer than MAX_PATH")); }
let mut buffer = [0u16; 260];
buffer[..wide.len()].copy_from_slice(&wide);
let side = px.min(256) as i32;
let mut icon: HICON = std::ptr::null_mut();
// SAFETY: `buffer` is NUL-terminated within MAX_PATH and `&mut icon` holds the 1 requested handle.
let extracted = unsafe { PrivateExtractIconsW(buffer.as_ptr(), 0, side, side, &mut icon, std::ptr::null_mut(), 1, 0) };
if extracted == 0 || extracted == u32::MAX || icon.is_null() { return Err(err("no icon")); }
// SAFETY: `ICONINFO` is a plain Win32 C struct whose all-zero representation is valid.
let mut info: ICONINFO = unsafe { std::mem::zeroed() };
// SAFETY: `icon` is a live `HICON` from `PrivateExtractIconsW` and `&mut info` is writable; any returned bitmaps are deleted below.
if unsafe { GetIconInfo(icon, &mut info) } == 0 {
// SAFETY: `icon` is owned by this function and unused after returning.
unsafe { DestroyIcon(icon) };
return Err(err("unreadable icon"));
}
let result = (|| {
if info.hbmColor.is_null() { return Err(err("monochrome icon")); }
// SAFETY: `BITMAP` is a plain Win32 C struct whose all-zero representation is valid.
let mut bitmap: BITMAP = unsafe { std::mem::zeroed() };
// SAFETY: `info.hbmColor` is a live non-null `HBITMAP` and `&raw mut bitmap` holds `size_of::<BITMAP>()` writable bytes.
if unsafe { GetObjectW(info.hbmColor, std::mem::size_of::<BITMAP>() as i32, (&raw mut bitmap).cast()) } == 0 {
return Err(err("unreadable icon bitmap"));
}
let (w, h) = (bitmap.bmWidth, bitmap.bmHeight);
if w <= 0 || h <= 0 || w > 1024 || h > 1024 { return Err(err("icon bitmap has no pixels")); }
let mut header = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: w,
biHeight: -h, // negative: rows top-down
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB,
// SAFETY: `BITMAPINFOHEADER` is a plain Win32 C struct whose remaining fields are valid when zeroed.
..unsafe { std::mem::zeroed() }
},
// SAFETY: `BITMAPINFO` is a plain Win32 C struct whose remaining color-table field is valid when zeroed.
..unsafe { std::mem::zeroed() }
};
let mut pixels = vec![0u8; w as usize * h as usize * 4];
// SAFETY: passing null creates a screen-compatible memory DC (or null on failure), deleted below.
let dc = unsafe { CreateCompatibleDC(std::ptr::null_mut()) };
// SAFETY: `info.hbmColor` is a live `w`×`h` bitmap, `pixels` holds `w * h * 4` writable bytes for the 32-bpp `header`, and a null `dc` returns 0.
let rows = unsafe { GetDIBits(dc, info.hbmColor, 0, h as u32, pixels.as_mut_ptr().cast(), &mut header, DIB_RGB_COLORS) };
// SAFETY: `dc` came from `CreateCompatibleDC` above and is not used afterwards.
unsafe { DeleteDC(dc) };
if rows == 0 { return Err(err("unreadable icon pixels")); }
// BGRA with straight alpha; icons without an alpha channel leave it zero and draw opaque.
let opaque = pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 0);
for p in pixels.as_chunks_mut::<4>().0 {
p.swap(0, 2);
if opaque { p[3] = 255; }
}
Ok((w as u32, h as u32, pixels))
})();
// SAFETY: `hbmColor` and `hbmMask` (when non-null) were created by `GetIconInfo`, and `icon` by `PrivateExtractIconsW`; none are used again.
unsafe {
if !info.hbmColor.is_null() { DeleteObject(info.hbmColor); }
if !info.hbmMask.is_null() { DeleteObject(info.hbmMask); }
DestroyIcon(icon);
}
result
}
#[cfg(target_os = "linux")]
fn linux_icon(path: &std::path::Path, px: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
let file = if path.extension().is_some_and(|e| e == "desktop") {
freedesktop::icon_file(path, px, &freedesktop::data_dirs())
.ok_or_else(|| ImageError(format!("no icon for {}", path.display())))?
} else { path.to_path_buf() };
let bytes = std::fs::read(&file).map_err(|e| ImageError(format!("{}: {e}", file.display())))?;
if bytes.len() > 16 << 20 { return Err(ImageError(format!("{} is too large for an icon", file.display()))); }
if super::has_svg_extension(&file) { return super::svg_rgba(&bytes, px); }
let image = image::load_from_memory(&bytes).map_err(|e| ImageError(format!("{}: {e}", file.display())))?.into_rgba8();
if image.width() > 1024 || image.height() > 1024 { return Err(ImageError(format!("{} is too large for an icon", file.display()))); }
Ok((image.width(), image.height(), image.into_raw()))
}
/// Freedesktop icon lookup: a `.desktop` entry's `Icon=` as an absolute path, or by name in the
/// hicolor theme (every size directory, `@2` included) and then `pixmaps`.
#[cfg(any(target_os = "linux", test))]
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) mod freedesktop {
use std::path::{Path, PathBuf};
pub(crate) fn data_dirs() -> Vec<PathBuf> {
let home = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share")));
let system = rune_core::env::var("XDG_DATA_DIRS").filter(|dirs| !dirs.is_empty())
.unwrap_or_else(|| "/usr/local/share:/usr/share".into());
home.into_iter().chain(system.split(':').filter(|d| !d.is_empty()).map(PathBuf::from)).collect()
}
/// The `Icon=` key of the `[Desktop Entry]` group.
pub(crate) fn icon_name(entry: &str) -> Option<&str> {
let mut group = "";
for line in entry.lines().map(str::trim) {
if line.starts_with('[') { group = line; continue; }
if group != "[Desktop Entry]" { continue; }
if let Some((key, value)) = line.split_once('=') && key.trim() == "Icon" {
return Some(value.trim()).filter(|v| !v.is_empty());
}
}
None
}
pub(crate) fn icon_file(entry: &Path, px: u32, data_dirs: &[PathBuf]) -> Option<PathBuf> {
let text = std::fs::read_to_string(entry).ok()?;
let name = icon_name(&text)?;
if Path::new(name).is_absolute() { return Path::new(name).is_file().then(|| name.into()); }
let name = name.strip_suffix(".png").or_else(|| name.strip_suffix(".svg")).unwrap_or(name);
// (effective pixel size, path); scalable sorts as "any size".
let mut found: Vec<(Option<u32>, PathBuf)> = Vec::new();
for dir in data_dirs {
let Ok(sizes) = std::fs::read_dir(dir.join("icons/hicolor")) else { continue };
for size in sizes.flatten() {
let label = size.file_name().to_string_lossy().into_owned();
let effective = if label == "scalable" { None } else {
let (dims, scale) = label.split_once('@').unwrap_or((&label, "1"));
let size = dims.split_once('x').and_then(|(w, _)| w.parse::<u32>().ok());
let Some(n) = size.zip(scale.parse::<u32>().ok()).map(|(w, s)| w * s.max(1)) else { continue };
Some(n)
};
for ext in ["png", "svg"] {
let file = size.path().join("apps").join(format!("{name}.{ext}"));
if file.is_file() { found.push((effective, file)); }
}
}
}
// Smallest bitmap that covers `px`, else scalable, else the largest bitmap.
let covering = found.iter().filter(|(n, _)| n.is_some_and(|n| n >= px)).min_by_key(|(n, _)| *n);
let scalable = found.iter().find(|(n, _)| n.is_none());
let largest = found.iter().max_by_key(|(n, _)| *n);
if let Some((_, file)) = covering.or(scalable).or(largest) { return Some(file.clone()); }
data_dirs.iter().flat_map(|dir| ["png", "svg"].map(|ext| dir.join(format!("pixmaps/{name}.{ext}")))).find(|f| f.is_file())
}
}
#[cfg(target_os = "macos")]
fn macos_icon(path: &std::path::Path, px: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
use objc2::runtime::{AnyObject, Bool};
use objc2::msg_send;
use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
let path = path.to_str().ok_or_else(|| ImageError("app icon path is not UTF-8".into()))?;
let workspace = macos_class(c"NSWorkspace")?;
// SAFETY: AppKit `NSWorkspace`, `NSImage`, and offscreen bitmap drawing run inside this
// autorelease pool (`macos_bitmap`'s precondition); `small` is a `px`×`px` RGBA8 bitmap whose
// `bitmapData` is non-null with `stride >= side * 4`, so every row slice is in bounds.
objc2::rc::autoreleasepool(|_| unsafe {
let workspace: *mut AnyObject = msg_send![workspace, sharedWorkspace];
let icon: *mut AnyObject = msg_send![workspace, iconForFile: &*NSString::from_str(path)];
if icon.is_null() { return Err(ImageError("NSWorkspace returned no icon".into())); }
let zero = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(0.0, 0.0));
// IconServices picks its rendition by the size asked for, and on macOS 26 and later a
// small size of an app without a modern icon is the "legacy" one: a shrunken tile in a
// grey frame. Draw at 256 pixels or more, then scale down.
let big = px.max(256);
// NSCompositingOperationCopy (1); a zero fromRect draws the whole best-fit representation.
let large = macos_bitmap(big, |_, rect| { let _: () = msg_send![icon, drawInRect: rect, fromRect: zero, operation: 1usize, fraction: 1.0f64]; })?;
let small = if big == px { large } else {
macos_bitmap(px, |ctx, rect| {
// NSImageInterpolationHigh.
let _: () = msg_send![ctx, setImageInterpolation: 3usize];
let none: *mut AnyObject = std::ptr::null_mut();
let _: Bool = msg_send![large, drawInRect: rect, fromRect: zero, operation: 1usize, fraction: 1.0f64, respectFlipped: Bool::NO, hints: none];
})?
};
let side = px as isize;
let data: *const u8 = msg_send![small, bitmapData];
let stride: isize = msg_send![small, bytesPerRow];
if data.is_null() || stride < side * 4 { return Err(ImageError("icon bitmap has no pixel data".into())); }
let mut out = Vec::with_capacity((px * px * 4) as usize);
for y in 0..side {
let row = std::slice::from_raw_parts(data.offset(y * stride), (side * 4) as usize);
for p in row.chunks_exact(4) {
let a = p[3];
let straight = |c: u8| if a == 0 { 0 } else { ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8 };
out.extend_from_slice(&[straight(p[0]), straight(p[1]), straight(p[2]), a]);
}
}
Ok((px, px, out))
})
}
#[cfg(target_os = "macos")]
fn macos_class(name: &std::ffi::CStr) -> Result<&'static objc2::runtime::AnyClass, ImageError> {
objc2::runtime::AnyClass::get(name).ok_or_else(|| ImageError(format!("{} is unavailable", name.to_string_lossy())))
}
/// A `side`×`side` sRGB bitmap with `draw(context, rect)` run into it as the current context.
/// Autoreleased: call inside an autorelease pool.
#[cfg(target_os = "macos")]
unsafe fn macos_bitmap(
side: u32,
draw: impl FnOnce(*mut objc2::runtime::AnyObject, objc2_foundation::NSRect),
) -> Result<*mut objc2::runtime::AnyObject, ImageError> {
use objc2::runtime::{AnyObject, Bool};
use objc2::rc::{Allocated, Retained};
use objc2::msg_send;
use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
let (bitmap, context, color_space) = (macos_class(c"NSBitmapImageRep")?, macos_class(c"NSGraphicsContext")?, macos_class(c"NSColorSpace")?);
let n = side as isize;
// SAFETY: AppKit bitmap and context calls on objects this function retains or that live in
// the caller's autorelease pool.
unsafe {
let rep: Allocated<AnyObject> = msg_send![bitmap, alloc];
let null: *mut *mut u8 = std::ptr::null_mut();
// Default bitmapFormat is premultiplied alpha-last RGBA, the only layout AppKit draws into.
let rep: Option<Retained<AnyObject>> = msg_send![rep,
initWithBitmapDataPlanes: null, pixelsWide: n, pixelsHigh: n, bitsPerSample: 8isize,
samplesPerPixel: 4isize, hasAlpha: Bool::YES, isPlanar: Bool::NO,
colorSpaceName: &*NSString::from_str("NSDeviceRGBColorSpace"), bitmapFormat: 0usize,
bytesPerRow: n * 4, bitsPerPixel: 32isize];
let rep = rep.ok_or_else(|| ImageError("could not allocate an icon bitmap".into()))?;
let srgb: *mut AnyObject = msg_send![color_space, sRGBColorSpace];
let tagged: *mut AnyObject = msg_send![&*rep, bitmapImageRepByRetaggingWithColorSpace: srgb];
let tagged = if tagged.is_null() { Retained::autorelease_return(rep) } else { tagged };
let ctx: *mut AnyObject = msg_send![context, graphicsContextWithBitmapImageRep: tagged];
if ctx.is_null() { return Err(ImageError("could not create an icon context".into())); }
let _: () = msg_send![context, saveGraphicsState];
let _: () = msg_send![context, setCurrentContext: ctx];
draw(ctx, NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(side as f64, side as f64)));
let _: () = msg_send![ctx, flushGraphics];
let _: () = msg_send![context, restoreGraphicsState];
Ok(tagged)
}
}
+31
View File
@@ -0,0 +1,31 @@
//! AVIF stills (`avif` feature), decoded by rav1d, a Rust port of dav1d, as straight-alpha
//! sRGB RGBA8. An animated AVIF shows its first frame.
use super::ImageError;
/// Whether `bytes` are an ISO-BMFF file of an AVIF brand.
pub(super) fn is_avif(bytes: &[u8]) -> bool {
bytes.len() >= 12 && &bytes[4..8] == b"ftyp" && matches!(&bytes[8..12], b"avif" | b"avis")
}
#[cfg(all(feature = "avif", not(target_arch = "wasm32")))]
pub(super) fn rgba(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), ImageError> {
use avif_decode::Image;
let error = |e: avif_decode::Error| ImageError(format!("AVIF: {e}"));
let image = avif_decode::Decoder::from_avif(bytes).map_err(error)?.to_image().map_err(error)?;
let eight = |v: u16| ((u32::from(v) * 255 + 32767) / 65535) as u8;
let (w, h, pixels): (usize, usize, Vec<u8>) = match image {
Image::Rgb8(i) => (i.width(), i.height(), i.pixels().flat_map(|p| [p.r, p.g, p.b, 255]).collect()),
Image::Rgba8(i) => (i.width(), i.height(), i.pixels().flat_map(|p| [p.r, p.g, p.b, p.a]).collect()),
Image::Rgb16(i) => (i.width(), i.height(), i.pixels().flat_map(|p| [eight(p.r), eight(p.g), eight(p.b), 255]).collect()),
Image::Rgba16(i) => (i.width(), i.height(), i.pixels().flat_map(|p| [eight(p.r), eight(p.g), eight(p.b), eight(p.a)]).collect()),
Image::Gray8(i) => (i.width(), i.height(), i.pixels().flat_map(|p| { let v = p.value(); [v, v, v, 255] }).collect()),
Image::Gray16(i) => (i.width(), i.height(), i.pixels().flat_map(|p| { let v = eight(p.value()); [v, v, v, 255] }).collect()),
};
if w == 0 || h == 0 || w > 8192 || h > 8192 { return Err(ImageError("AVIF is too large".into())); }
Ok((w as u32, h as u32, pixels))
}
#[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))]
pub(super) fn rgba(_: &[u8]) -> Result<(u32, u32, Vec<u8>), ImageError> {
Err(ImageError("AVIF images need rune's `avif` feature".into()))
}
+45
View File
@@ -0,0 +1,45 @@
// `url` (relative to the page) decoded by the browser's own codecs, which run off the main
// thread: `[width, height, rgba]` with straight-alpha sRGB RGBA bytes, upright by EXIF. SVG comes
// back as `[0, 0, bytes]` for Rune to rasterize. Images over `maxSide` a side are refused
// before their pixels are read. It resolves in a task of its own, so Rune's work on one image
// (its mips) never runs in the same long task as another's or a frame's.
export async function fetchImage(url, maxSide) {
const reply = await readImage(url, maxSide);
await nextTask();
return reply;
}
async function readImage(url, maxSide) {
const response = await fetch(new URL(url, document.baseURI));
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
const type = (response.headers.get('content-type') || blob.type).split(';')[0].trim().toLowerCase();
const path = response.url ? new URL(response.url).pathname : '';
if (type === 'image/svg+xml' || /\.svgz?$/i.test(path)) return [0, 0, new Uint8Array(await blob.arrayBuffer())];
return blobRgba(blob, maxSide);
}
export async function decodeImage(bytes, maxSide) {
const reply = await blobRgba(new Blob([bytes]), maxSide);
await nextTask();
return reply;
}
async function blobRgba(blob, maxSide) {
const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image', colorSpaceConversion: 'default' });
try {
const { width, height } = bitmap;
if (width > maxSide || height > maxSide) throw new Error(`${width}×${height} is over ${maxSide} pixels a side`);
const canvas = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(width, height)
: Object.assign(document.createElement('canvas'), { width, height });
const context = canvas.getContext('2d', { willReadFrequently: true });
context.drawImage(bitmap, 0, 0);
return [width, height, new Uint8Array(context.getImageData(0, 0, width, height).data.buffer)];
} finally {
bitmap.close();
}
}
export function nextTask() {
return globalThis.scheduler?.yield ? globalThis.scheduler.yield() : new Promise((resolve) => setTimeout(resolve, 0));
}
+180
View File
@@ -0,0 +1,180 @@
//! `ImageCache::url`: an image by URL. On web the browser fetches it and decodes it with its
//! own codecs (`createImageBitmap`, so WebP and AVIF too) off the main thread, and the straight
//! RGBA lands through the same mip path as `ImageCache::rgba`. On native a URL without a scheme
//! is a path and a `file:` URL names one; both load like `ImageCache::file`.
use super::{Decoded, Image, ImageCache, ImageError, Input, icon_pixels, mip_chain, svg_rgba};
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(module = "/src/from_url.js")]
extern "C" {
/// Resolves to `[width, height, Uint8Array]`: straight sRGB RGBA, or `[0, 0, svg bytes]`.
#[wasm_bindgen(js_name = fetchImage)]
fn fetch_image(url: &str, max_side: u32) -> js_sys::Promise;
/// Resolves to `[width, height, Uint8Array]`, straight sRGB RGBA the browser decoded from
/// encoded image bytes (JPEG, WebP, AVIF, GIF's first frame).
#[wasm_bindgen(js_name = decodeImage)]
fn decode_image(bytes: &[u8], max_side: u32) -> js_sys::Promise;
/// Resolves in a later task, letting the browser draw and handle input in between.
#[wasm_bindgen(js_name = nextTask)]
fn next_task() -> js_sys::Promise;
}
/// The largest side a fetched image may have, as for decoded files: 8192 pixels, so at most
/// 256 MiB of decoded RGBA before mips.
#[cfg_attr(not(any(test, target_arch = "wasm32")), allow(dead_code))]
pub(super) const MAX_SIDE: u32 = 8192;
impl ImageCache {
/// The image at `url`, shared by URL, size and scale like [`ImageCache::file`] (SVG
/// rasterizes to fit `size_pt` at `scale`; other formats ignore both). Pending until it
/// arrives, then the cache's waker redraws.
///
/// On web the browser fetches `url`, relative to the page, and decodes it off the main
/// thread: PNG, JPEG, GIF's first frame, WebP and AVIF, whatever the browser reads, turned
/// upright by EXIF orientation. `image/svg+xml` and `.svg`/`.svgz` URLs rasterize with
/// Rune's SVG renderer. Images over 8192 pixels a side, failed requests and cross-origin
/// images without CORS resolve to [`Image::error`]. On native, where Rune has no HTTP
/// client, a path or `file:` URL loads like [`ImageCache::file`] and other URLs fail; fetch
/// those bytes yourself and call [`ImageCache::load`].
pub fn url(&self, url: &str, size_pt: f32, scale: f32) -> Image {
let px = icon_pixels(size_pt, scale);
let mut hash = blake3::Hasher::new();
hash.update(b"rune-url\0");
hash.update(url.as_bytes());
hash.update(&[0]);
hash.update(&px.to_le_bytes());
self.request(*hash.finalize().as_bytes(), Input::Url(url.to_owned(), px))
}
/// One image in several sizes, as an HTML `srcset`: `sources` are `(url, width in pixels)`,
/// and this loads the narrowest at least `size_pt × scale` pixels wide (or the widest), as
/// [`ImageCache::url`]. Pass the width the image shows at, so a phone fetches the small
/// file; images are shared by the file chosen, so a window resizing within one file's range
/// loads nothing new. An `--html` export writes every source, so the browser picks one
/// too. SVG sources rasterize at their listed width.
pub fn url_set(&self, sources: &[(&str, u32)], size_pt: f32, scale: f32) -> Image {
let need = (size_pt * scale).ceil();
let mut sorted = sources.to_vec();
sorted.sort_by_key(|s| s.1);
let Some(&(url, width)) = sorted.iter().find(|s| s.1 as f32 >= need).or(sorted.last()) else {
return self.url("", size_pt, scale);
};
let srcset: String = sorted.iter().map(|(u, w)| format!("{u} {w}w")).collect::<Vec<_>>().join(", ");
let mut hash = blake3::Hasher::new();
hash.update(b"rune-url-set\0");
hash.update(url.as_bytes());
hash.update(&[0]);
hash.update(srcset.as_bytes());
self.request_set(*hash.finalize().as_bytes(), Input::Url(url.to_owned(), width.max(1)), Some(srcset.into()))
}
}
/// What the browser handed back for a URL.
#[cfg_attr(not(any(test, target_arch = "wasm32")), allow(dead_code))]
pub(super) enum Fetched {
/// Straight-alpha sRGB RGBA8 the browser decoded.
Rgba(u32, u32, Vec<u8>),
/// SVG or SVGZ bytes, which Rune rasterizes at `px`.
Svg(Vec<u8>),
}
/// The mips for a fetched image, or why not, naming the URL.
#[cfg_attr(not(test), allow(dead_code))]
pub(super) fn land(url: &str, fetched: Fetched, px: u32) -> Result<Decoded, ImageError> {
match fetched {
Fetched::Rgba(w, h, bytes) => mip_chain(w, h, &bytes),
Fetched::Svg(bytes) => svg_rgba(&bytes, px).and_then(|(w, h, bytes)| mip_chain(w, h, &bytes)),
}
.map_err(|e| ImageError(format!("{url}: {e}")))
}
/// [`land`] on the browser's main thread, where frames draw too: the mips are built a slice at
/// a time with a task between slices, so no slice holds a frame or input up for long.
#[cfg(target_arch = "wasm32")]
pub(super) async fn land_in_slices(url: &str, fetched: Fetched, px: u32) -> Result<Decoded, ImageError> {
/// About a few milliseconds of mip work on a phone.
const SLICE: usize = 1 << 15;
let named = |e: ImageError| ImageError(format!("{url}: {e}"));
let (w, h, bytes) = match fetched {
Fetched::Rgba(w, h, bytes) => (w, h, bytes),
Fetched::Svg(bytes) => svg_rgba(&bytes, px).map_err(named)?,
};
let mut steps = super::mips::MipSteps::new(w, h, &bytes).map_err(named)?;
while !steps.step(SLICE) {
wasm_bindgen_futures::JsFuture::from(next_task()).await.ok();
}
Ok(steps.finish())
}
/// Fetch and decode `url` in the browser, resolving in a task of its own so each image's mips
/// are a separate piece of main-thread work.
#[cfg(target_arch = "wasm32")]
pub(super) async fn fetch(url: &str) -> Result<Fetched, ImageError> {
browser_reply(url, fetch_image(url, MAX_SIDE)).await
}
/// Encoded image bytes decoded by the browser's own codecs, off the main thread, so a web build
/// carries no JPEG decoder of its own.
#[cfg(target_arch = "wasm32")]
pub(super) async fn decode_in_browser(bytes: &[u8]) -> Result<Fetched, ImageError> {
browser_reply("image", decode_image(bytes, MAX_SIDE)).await
}
#[cfg(target_arch = "wasm32")]
async fn browser_reply(url: &str, promise: js_sys::Promise) -> Result<Fetched, ImageError> {
use wasm_bindgen::JsCast;
let reply = wasm_bindgen_futures::JsFuture::from(promise).await.map_err(|e| {
let why = e.dyn_ref::<js_sys::Error>().map_or_else(|| format!("{e:?}"), |e| String::from(e.message()));
ImageError(format!("{url}: {why}"))
})?;
let reply: js_sys::Array = reply.unchecked_into();
let side = |i| reply.get(i).as_f64().unwrap_or(0.0) as u32;
let bytes = reply.get(2).unchecked_into::<js_sys::Uint8Array>().to_vec();
Ok(if side(0) == 0 { Fetched::Svg(bytes) } else { Fetched::Rgba(side(0), side(1), bytes) })
}
/// The file a native `url` names: a path with no scheme, or a `file:` URL.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(super) fn file_path(url: &str) -> Result<std::path::PathBuf, ImageError> {
let scheme = url.split_once(':').map(|(s, _)| s)
// A one-letter "scheme" is a Windows drive.
.filter(|s| s.len() > 1 && s.starts_with(|c: char| c.is_ascii_alphabetic())
&& s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')));
let Some(scheme) = scheme else { return Ok(url.into()) };
let unsupported = || ImageError(format!("{url}: only web fetches URLs; on native fetch the bytes and call ImageCache::load"));
if !scheme.eq_ignore_ascii_case("file") { return Err(unsupported()); }
let rest = &url[scheme.len() + 1..];
let path = match rest.strip_prefix("//") {
Some(rest) => rest.strip_prefix("localhost").unwrap_or(rest),
None => rest,
};
if !path.starts_with('/') { return Err(unsupported()); }
let path = percent_decode(path).ok_or_else(|| ImageError(format!("{url}: not a valid file URL")))?;
// `file:///C:/x` names `C:/x` on Windows.
#[cfg(windows)]
let path = match path.as_bytes() { [b'/', d, b':', ..] if d.is_ascii_alphabetic() => path[1..].to_owned(), _ => path };
Ok(path.into())
}
/// The bytes of the font file a native `url` names (`App::font_url`).
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub fn font_file(url: &str) -> Result<Vec<u8>, ImageError> {
let path = file_path(url)?;
std::fs::read(&path).map_err(|e| ImageError(format!("{}: {e}", path.display())))
}
fn percent_decode(s: &str) -> Option<String> {
let mut out = Vec::with_capacity(s.len());
let mut bytes = s.bytes();
while let Some(b) = bytes.next() {
if b != b'%' { out.push(b); continue; }
let digit = |b: Option<u8>| (b? as char).to_digit(16);
out.push((digit(bytes.next())? * 16 + digit(bytes.next())?) as u8);
}
String::from_utf8(out).ok()
}
#[cfg(test)]
#[path = "from_url_tests.rs"]
mod tests;
+70
View File
@@ -0,0 +1,70 @@
use super::*;
use std::sync::Arc;
#[test]
fn fetched_pixels_land_as_mips_and_oversized_or_short_ones_fail_naming_the_url() {
let decoded = land("a.webp", Fetched::Rgba(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]), 1).unwrap();
assert_eq!((decoded.mips[0].width, decoded.mips[0].height), (2, 1));
assert_eq!(decoded.mips.len(), 2);
let side = MAX_SIDE + 1;
let huge = land("huge.avif", Fetched::Rgba(side, 1, vec![0; side as usize * 4]), 1).err().unwrap();
assert!(huge.0.starts_with("huge.avif: "), "{huge}");
assert!(land("short.png", Fetched::Rgba(2, 2, vec![0; 4]), 1).is_err(), "byte length must match the size");
}
#[cfg(feature = "svg")]
#[test]
fn fetched_svg_rasterizes_at_the_requested_size() {
const SVG: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="8"><rect width="16" height="8" fill="#fff"/></svg>"##;
let decoded = land("mark.svg", Fetched::Svg(SVG.to_vec()), 48).unwrap();
assert_eq!((decoded.mips[0].width, decoded.mips[0].height), (48, 24));
assert!(land("bad.svg", Fetched::Svg(b"<svg".to_vec()), 48).err().unwrap().0.starts_with("bad.svg: "));
}
#[test]
fn native_urls_name_files_and_refuse_the_network() {
assert_eq!(file_path("assets/logo.png").unwrap(), std::path::PathBuf::from("assets/logo.png"));
#[cfg(not(windows))]
{
assert_eq!(file_path("file:///tmp/a%20b.png").unwrap(), std::path::PathBuf::from("/tmp/a b.png"));
assert_eq!(file_path("FILE://localhost/tmp/x.png").unwrap(), std::path::PathBuf::from("/tmp/x.png"));
}
assert_eq!(file_path(r"C:\art\x.png").unwrap(), std::path::PathBuf::from(r"C:\art\x.png"), "a drive letter isn't a scheme");
for url in ["https://example.com/a.png", "data:image/png;base64,AAAA", "file:relative.png", "file:///bad%zz.png"] {
assert!(file_path(url).is_err(), "{url}");
}
}
#[test]
fn the_cache_loads_a_url_once_and_wakes_when_it_lands() {
let dir = std::env::temp_dir().join(format!("rune-image-url-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("dot.png");
image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255])).save(&path).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let cache = ImageCache::new(Arc::new(move || { tx.send(()).ok(); }));
let by_path = cache.url(path.to_str().unwrap(), 16.0, 2.0);
assert!(Arc::ptr_eq(&by_path.0, &cache.url(path.to_str().unwrap(), 16.0, 2.0).0), "one handle per URL, size and scale");
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
assert_eq!(by_path.size(), Some([3, 2]));
#[cfg(not(windows))]
assert_eq!(cache.url(&format!("file://{}", path.display()), 16.0, 2.0).wait(), Ok([3, 2]));
let remote = cache.url("https://example.com/dot.png", 16.0, 2.0);
assert!(remote.wait().unwrap_err().0.contains("ImageCache::load"));
assert_eq!(remote.pixels().source_url(), Some("https://example.com/dot.png"), "the URL stays readable for a page export");
assert_eq!(cache.rgba(1, 1, vec![0; 4]).pixels().source_url(), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_source_set_loads_the_narrowest_wide_enough_and_keeps_every_size() {
let cache = ImageCache::new(Arc::new(|| {}));
let sources = [("https://example.com/a-1280.avif", 1280), ("https://example.com/a-640.avif", 640)];
let phone = cache.url_set(&sources, 300.0, 2.0);
assert_eq!(phone.pixels().source_url(), Some("https://example.com/a-640.avif"));
assert_eq!(phone.pixels().source_set(), Some("https://example.com/a-640.avif 640w, https://example.com/a-1280.avif 1280w"));
assert!(Arc::ptr_eq(&phone.0, &cache.url_set(&sources, 310.0, 2.0).0), "one handle per chosen file");
assert_eq!(cache.url_set(&sources, 400.0, 2.0).pixels().source_url(), Some("https://example.com/a-1280.avif"));
assert_eq!(cache.url_set(&sources, 900.0, 2.0).pixels().source_url(), Some("https://example.com/a-1280.avif"), "the widest when none is wide enough");
assert_eq!(cache.url("https://example.com/a-640.avif", 300.0, 2.0).pixels().source_set(), None);
}
+697
View File
@@ -0,0 +1,697 @@
//! Content-addressed image decoding, linear-light mip generation, dynamic pixel buffers
//! (`pixels`), SVG and AVIF codecs, OS app icon rasterization and surface placement math. Decode
//! and mip generation run off the UI thread on shared decoder workers, never in a view or a render
//! frame. Apps normally reach this crate through `rune` (`rune::image`, `rune::Pixels`).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
#[cfg(all(test, not(target_arch = "wasm32")))]
use std::sync::mpsc;
pub(crate) mod animated;
mod app_icon;
mod avif;
mod from_url;
#[cfg(test)]
mod mip_tests;
mod mips;
#[doc(hidden)]
pub mod pixels;
#[doc(hidden)]
pub mod place;
#[cfg(test)]
mod tests;
pub use app_icon::app_icon_rgba;
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
pub use from_url::font_file;
pub use pixels::Pixels;
pub use place::Align;
pub use place::SurfaceFit;
#[cfg(test)]
use mips::byte;
use mips::mip_chain;
pub type ImageId = [u8; 32];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageError(pub String);
impl std::fmt::Display for ImageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) }
}
impl std::error::Error for ImageError {}
/// Pixels are sRGB-encoded *linear-premultiplied* RGB plus linear alpha. Sampling with
/// Rgba8UnormSrgb yields linear-premultiplied RGBA, including between mip levels.
pub(crate) struct Mip {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
pub(crate) struct Decoded {
/// The image, or an animation's first frame.
pub mips: Vec<Mip>,
/// An animation's other frames and timing.
pub motion: Option<Box<animated::Motion>>,
}
struct State {
id: ImageId,
pixels: Pixels,
decoded: OnceLock<Result<Arc<Decoded>, ImageError>>,
}
/// A cheap shared handle. Pending images paint nothing until their worker wakes the app.
#[derive(Clone)]
pub struct Image(Arc<State>, Pixels);
impl std::fmt::Debug for Image {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Image").field("id", &self.id()).field("size", &self.size()).finish()
}
}
impl Image {
/// A handle on `state`, whose pixels keep it in the cache while drawn.
fn new(state: Arc<State>) -> Image {
let pixels = state.pixels.clone().keeping(state.clone());
Image(state, pixels)
}
/// The shared static pixel handle, ready to pass to `El::pixels` after decoding. While
/// any clone of it lives (an element drawing it), the cache hands back this image.
pub fn pixels(&self) -> &Pixels { &self.1 }
pub fn id(&self) -> ImageId { self.0.id }
pub fn size(&self) -> Option<[u32; 2]> {
let mip = self.decoded()?.ok()?.mips.first()?;
Some([mip.width, mip.height])
}
pub fn is_ready(&self) -> bool { self.0.decoded.get().is_some() }
pub fn error(&self) -> Option<&ImageError> { self.0.decoded.get()?.as_ref().err() }
/// Wait for fixture assets before advancing a deterministic headless scene. Interactive
/// apps use the cache's waker instead; decode still happens on the cache worker.
pub fn wait(&self) -> Result<[u32; 2], &ImageError> {
#[cfg(target_arch = "wasm32")]
let decoded = self.0.decoded.get().expect("Image::wait cannot block on web; use is_ready and the cache waker");
#[cfg(not(target_arch = "wasm32"))]
let decoded = self.0.decoded.wait();
let mip = &decoded.as_ref()?.mips[0];
Ok([mip.width, mip.height])
}
pub(crate) fn decoded(&self) -> Option<Result<&Decoded, &ImageError>> {
self.0.decoded.get().map(|r| r.as_ref().map(Arc::as_ref))
}
// The handle is ready before its pixels wake any window, so a woken frame sees its size.
fn finish(&self, decoded: Result<Decoded, ImageError>) {
let decoded = decoded.map(Arc::new);
let mips = decoded.as_ref().ok().cloned();
self.0.decoded.set(decoded).ok();
if let Some(mips) = mips { self.0.pixels.set_mips(mips); }
}
}
enum Input {
Encoded(Arc<[u8]>),
Rgba(u32, u32, Arc<[u8]>),
Icon(#[cfg_attr(target_arch = "wasm32", allow(dead_code))] std::path::PathBuf, #[cfg_attr(target_arch = "wasm32", allow(dead_code))] u32),
Svg(Arc<[u8]>, u32),
#[cfg(not(target_arch = "wasm32"))]
File(std::path::PathBuf, u32),
/// `ImageCache::url`, and `ImageCache::file` on web.
Url(String, u32),
/// A decoder that panics, standing in for a codec bug.
#[cfg(test)]
Panic,
#[cfg(all(test, not(target_arch = "wasm32")))]
Gated(Box<Input>, mpsc::Receiver<()>),
}
impl Input {
fn decode(self) -> Result<Decoded, ImageError> {
match self {
Input::Encoded(bytes) => decode(&bytes),
Input::Rgba(w, h, bytes) => mip_chain(w, h, &bytes),
Input::Svg(bytes, px) => svg_rgba(&bytes, px).and_then(|(w, h, bytes)| mip_chain(w, h, &bytes)),
#[cfg(not(target_arch = "wasm32"))]
Input::Icon(path, px) => app_icon_rgba(&path, px).and_then(|(w, h, bytes)| mip_chain(w, h, &bytes)),
#[cfg(not(target_arch = "wasm32"))]
Input::File(path, px) => {
let bytes = std::fs::read(&path).map_err(|e| ImageError(format!("{}: {e}", path.display())))?;
if has_svg_extension(&path) || is_svg(&bytes) {
svg_rgba(&bytes, px).and_then(|(w, h, bytes)| mip_chain(w, h, &bytes))
} else {
decode(&bytes)
}
}
#[cfg(not(target_arch = "wasm32"))]
Input::Url(url, px) => Input::File(from_url::file_path(&url)?, px).decode(),
#[cfg(target_arch = "wasm32")]
Input::Icon(..) => Err(ImageError("filesystem images are unsupported on web".into())),
// Fetched asynchronously by `ImageCache::request`.
#[cfg(target_arch = "wasm32")]
Input::Url(url, _) => Err(ImageError(format!("{url}: fetched, not decoded"))),
#[cfg(test)]
Input::Panic => panic!("decoder bug"),
#[cfg(all(test, not(target_arch = "wasm32")))]
Input::Gated(input, release) => {
release.recv().map_err(|_| ImageError("test gate dropped".into()))?;
input.decode()
}
}
}
/// `decode`, with a panic in a codec (a malformed file can still trip one) failing this
/// image instead of unwinding the worker, which would leave it pending and fail every later one.
#[cfg(not(target_arch = "wasm32"))]
fn decode_caught(self) -> Result<Decoded, ImageError> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.decode())).unwrap_or_else(|panic| {
let why = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
Err(ImageError(format!("image decoder panicked: {}", why.unwrap_or("no message"))))
})
}
}
#[cfg(not(target_arch = "wasm32"))]
struct Job { image: Image, input: Input, waker: rune_core::Waker }
/// Decoder threads for the process, at most one per core.
#[cfg(not(target_arch = "wasm32"))]
const DECODERS: usize = 4;
/// Straight RGBA images up to this many pixels (64 x 64) finish on the calling thread.
#[cfg(not(target_arch = "wasm32"))]
const INLINE_RGBA_PIXELS: u64 = 64 * 64;
/// The images waiting to decode, shared by every cache, and how many decoders are draining them.
/// A decoder is a task on Rune's shared threads (`task::spawn`) that decodes until none is left:
/// a session opening on several screenshots decodes them side by side, and with nothing to
/// decode no thread stays for it (each kept decoder thread held its stack and its allocator
/// pages for the process's life). Task threads reserve the stack `MAX_SVG_DEPTH` needs
/// (`rune_core::task`'s `STACK`).
#[cfg(not(target_arch = "wasm32"))]
static DECODING: Mutex<(std::collections::VecDeque<Job>, usize)> = Mutex::new((std::collections::VecDeque::new(), 0));
/// Queues `job`, and starts a decoder for it while fewer than one per core (at most
/// [`DECODERS`]) run. False when no decoder runs and none could start.
#[cfg(not(target_arch = "wasm32"))]
fn decode_later(job: Job) -> bool {
let mut d = DECODING.lock().unwrap_or_else(|e| e.into_inner());
d.0.push_back(job);
let most = DECODERS.min(std::thread::available_parallelism().map_or(1, |n| n.get()));
if d.1 >= most {
return true;
}
d.1 += 1;
drop(d);
if rune_core::task::spawn("rune-images", decode_jobs).is_ok() {
return true;
}
let mut d = DECODING.lock().unwrap_or_else(|e| e.into_inner());
d.1 -= 1;
if d.1 > 0 {
return true;
}
d.0.pop_back();
false
}
#[cfg(not(target_arch = "wasm32"))]
fn decode_jobs() {
loop {
let job = {
let mut d = DECODING.lock().unwrap_or_else(|e| e.into_inner());
let Some(job) = d.0.pop_front() else {
d.1 -= 1;
return;
};
job
};
job.image.finish(job.input.decode_caught());
(job.waker)();
}
}
/// Construct once during app setup. The cache deduplicates by content, not a path or pointer;
/// dropping all handles releases decoded pixels. Its images decode on the process's decoder
/// threads, which every cache shares. The waker should be the one supplied by `AppSpec::setup`.
pub struct ImageCache {
entries: Mutex<HashMap<ImageId, Weak<State>>>,
#[cfg(not(target_arch = "wasm32"))]
waker: rune_core::Waker,
#[cfg(target_arch = "wasm32")]
wake: rune_core::Waker,
}
impl ImageCache {
#[cfg(target_arch = "wasm32")]
pub fn new(wake: rune_core::Waker) -> Self {
Self { entries: Mutex::new(HashMap::new()), wake }
}
#[cfg(not(target_arch = "wasm32"))]
pub fn new(waker: rune_core::Waker) -> Self {
Self { entries: Mutex::new(HashMap::new()), waker }
}
/// PNG (APNG animates), JPEG, GIF and WebP (both animate), BMP, ICO, AVIF (with the `avif`
/// feature; its first frame), modern ICNS containing a PNG representation, or SVG (plain or
/// gzipped SVGZ, recognised by its content). An SVG rasterizes at twice its own size; use
/// [`ImageCache::svg`] to rasterize it at the size it draws at. Legacy ICNS codecs return an
/// explicit error; callers can provide platform-decoded RGBA instead. An animation decodes
/// every frame on the worker, and plays only while an element draws it in a shown window.
/// On web the browser decodes everything but PNG, SVG and ICNS, so GIF and WebP show their
/// first frame there.
pub fn load(&self, bytes: impl Into<Arc<[u8]>>) -> Image {
let bytes = bytes.into();
let mut hash = blake3::Hasher::new();
hash.update(b"rune-encoded\0");
hash.update(&bytes);
let id = *hash.finalize().as_bytes();
self.request(id, Input::Encoded(bytes))
}
/// SVG or SVGZ bytes rasterized to fit `size_pt` points square at `scale` device pixels per
/// point (pass the window's `Env::scale`), keeping the drawing's aspect ratio.
/// Rasterize at the largest size the image draws at: smaller draws use its mips, so 16 pt at
/// 2× stays crisp. Handles are shared by content, size and scale.
pub fn svg(&self, bytes: impl Into<Arc<[u8]>>, size_pt: f32, scale: f32) -> Image {
let bytes = bytes.into();
let px = icon_pixels(size_pt, scale);
let mut hash = blake3::Hasher::new();
hash.update(b"rune-svg\0");
hash.update(&px.to_le_bytes());
hash.update(&bytes);
self.request(*hash.finalize().as_bytes(), Input::Svg(bytes, px))
}
/// Bytes with a MIME type, as from a data URL or a `Content-Type` header: `image/svg+xml`
/// rasterizes like [`ImageCache::svg`], anything else decodes like [`ImageCache::load`].
pub fn load_mime(&self, bytes: impl Into<Arc<[u8]>>, mime: &str, size_pt: f32, scale: f32) -> Image {
let essence = mime.split(';').next().unwrap_or("").trim();
if essence.eq_ignore_ascii_case("image/svg+xml") { self.svg(bytes, size_pt, scale) } else { self.load(bytes) }
}
/// An image file, read and decoded on the worker. `.svg` and `.svgz` files (or SVG content)
/// rasterize like [`ImageCache::svg`]; other formats decode like [`ImageCache::load`], ignoring
/// the size. Handles are shared by path, size and scale, so an edited file needs a new handle
/// once the old ones drop. On web the path is a URL relative to the page, fetched as
/// [`ImageCache::url`] does, so `cache.file("assets/logo.webp", ..)` works in both builds.
pub fn file(&self, path: impl AsRef<std::path::Path>, size_pt: f32, scale: f32) -> Image {
let path = path.as_ref().to_path_buf();
let px = icon_pixels(size_pt, scale);
let mut hash = blake3::Hasher::new();
hash.update(b"rune-file\0");
hash.update(path.as_os_str().as_encoded_bytes());
hash.update(&[0]);
hash.update(&px.to_le_bytes());
#[cfg(target_arch = "wasm32")]
let input = Input::Url(path.to_string_lossy().into_owned(), px);
#[cfg(not(target_arch = "wasm32"))]
let input = Input::File(path, px);
self.request(*hash.finalize().as_bytes(), input)
}
/// Straight-alpha sRGB RGBA8. Validation, premultiplication and mips happen off-thread.
pub fn rgba(&self, width: u32, height: u32, bytes: impl Into<Arc<[u8]>>) -> Image {
let bytes = bytes.into();
let mut hash = blake3::Hasher::new();
hash.update(b"rune-rgba8\0");
hash.update(&width.to_le_bytes());
hash.update(&height.to_le_bytes());
hash.update(&bytes);
self.request(*hash.finalize().as_bytes(), Input::Rgba(width, height, bytes))
}
/// The Finder icon for an app bundle or any file path, rasterized at 2× `size_pt`.
/// See [`ImageCache::app_icon_scaled`].
pub fn app_icon(&self, path: impl AsRef<std::path::Path>, size_pt: f32) -> Image {
self.app_icon_scaled(path, size_pt, 2.0)
}
/// The Finder icon for `path`, rasterized at `size_pt * scale` pixels square (pass the
/// window's display scale). Handles are shared by (path, size, scale) rather than by
/// content, so repeated calls never re-rasterize while a handle is alive. Lookup and
/// rasterization run on the cache worker like any decode, so this is safe to call from a view.
/// Missing paths still get the system's generic document icon on macOS. Windows reads an
/// executable's or icon file's first icon; Linux reads a `.desktop` entry's `Icon=` from the
/// hicolor theme or pixmaps (PNG or SVG), or an image file itself. Paths without an icon
/// resolve to an error, so callers can draw their own fallback.
pub fn app_icon_scaled(&self, path: impl AsRef<std::path::Path>, size_pt: f32, scale: f32) -> Image {
let path = path.as_ref().to_path_buf();
let px = icon_pixels(size_pt, scale);
let mut hash = blake3::Hasher::new();
hash.update(b"rune-app-icon\0");
hash.update(path.as_os_str().as_encoded_bytes());
hash.update(&[0]);
hash.update(&size_pt.to_bits().to_le_bytes());
hash.update(&scale.to_bits().to_le_bytes());
self.request(*hash.finalize().as_bytes(), Input::Icon(path, px))
}
fn request(&self, id: ImageId, input: Input) -> Image {
self.request_set(id, input, None)
}
fn request_set(&self, id: ImageId, input: Input, srcset: Option<Arc<str>>) -> Image {
let mut entries = self.entries.lock().unwrap();
if let Some(state) = entries.get(&id).and_then(Weak::upgrade) { return Image::new(state); }
entries.retain(|_, value| value.strong_count() > 0);
let url: Option<Arc<str>> = match &input {
Input::Url(url, _) => Some(url.as_str().into()),
#[cfg(not(target_arch = "wasm32"))]
Input::File(path, _) => Some(path.to_string_lossy().into()),
_ => None,
};
let image = Image::new(Arc::new(State { id, pixels: Pixels::from_url(url, srcset), decoded: OnceLock::new() }));
entries.insert(id, Arc::downgrade(&image.0));
// A small straight RGBA image (a 16 pt tile at 2x) is ready at once: its mips take
// microseconds, less than handing it to a decoder, and the view that asked for it draws it
// in the same frame rather than a placeholder first. It still wakes the app once, as a
// decoded one does: a caller outside a view's build (an overlay's state, a poll) is
// redrawn by that wake alone.
#[cfg(not(target_arch = "wasm32"))]
if let Input::Rgba(w, h, _) = &input && u64::from(*w) * u64::from(*h) <= INLINE_RGBA_PIXELS {
image.finish(input.decode_caught());
drop(entries);
(self.waker)();
return image;
}
#[cfg(not(target_arch = "wasm32"))]
if !decode_later(Job { image: image.clone(), input, waker: self.waker.clone() }) {
image.0.decoded.set(Err(ImageError("image worker stopped".into()))).ok();
}
#[cfg(target_arch = "wasm32")]
{
// The task holds the image weakly, so a request dropped before it runs (a view's
// guess, replaced in the same frame once layout knows the size) fetches nothing,
// and one dropped while its bytes download is never decoded.
let weak = Arc::downgrade(&image.0);
let wake = self.wake.clone();
wasm_bindgen_futures::spawn_local(async move {
let decoded = match input {
Input::Url(url, px) => {
if !wanted(&weak) { return; }
let fetched = from_url::fetch(&url).await;
if !wanted(&weak) { return; }
match fetched { Ok(fetched) => from_url::land_in_slices(&url, fetched, px).await, Err(e) => Err(e) }
}
Input::Encoded(bytes) if browser_decodes(&bytes) => {
let decoded = from_url::decode_in_browser(&bytes).await;
if !wanted(&weak) { return; }
match decoded { Ok(fetched) => from_url::land_in_slices("image", fetched, 0).await, Err(e) => Err(e) }
}
input => input.decode(),
};
let Some(state) = weak.upgrade() else { return };
Image::new(state).finish(decoded);
wake();
});
}
image
}
}
/// Encoded bytes a web build hands to the browser's codecs: everything but PNG (decoded exactly,
/// alpha and all, by Rune), SVG and ICNS.
#[cfg_attr(not(any(test, target_arch = "wasm32")), allow(dead_code))]
fn browser_decodes(bytes: &[u8]) -> bool {
!bytes.starts_with(b"\x89PNG\r\n\x1a\n") && !bytes.starts_with(b"icns") && !is_svg(bytes)
}
/// Whether anything still holds the image a fetch is for.
#[cfg_attr(not(any(test, target_arch = "wasm32")), allow(dead_code))]
fn wanted(state: &std::sync::Weak<State>) -> bool { state.strong_count() > 0 }
fn icon_pixels(size_pt: f32, scale: f32) -> u32 {
let px = (size_pt * scale).ceil();
if px.is_finite() { px.clamp(1.0, 1024.0) as u32 } else { 1 }
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn has_svg_extension(path: &std::path::Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("svg") || e.eq_ignore_ascii_case("svgz"))
}
/// Gzip (SVGZ), or markup after an optional BOM and whitespace. No raster format starts with `<`.
fn is_svg(bytes: &[u8]) -> bool {
if bytes.starts_with(&[0x1f, 0x8b]) { return true; }
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'<')
}
/// Options for `usvg` that resolve nothing outside the SVG's own bytes: non-`data:` `<image>` and
/// `<feImage>` `href`s never touch the filesystem or UNC paths, and `data:` URLs accept raster
/// formats only (`image/svg+xml` and `text/plain` SVG fall-through are refused).
///
/// Rune builds `resvg` with `raster-images` off, so those raster arms are resolved in the tree but
/// never drawn today; they—and raster decoder pixel/memory bounds—become live if `raster-images` is
/// ever enabled (for example via feature unification).
#[cfg(feature = "svg")]
fn svg_options() -> resvg::usvg::Options<'static> {
use resvg::usvg::{ImageHrefResolver, ImageKind, Options};
let raster = |data: Arc<Vec<u8>>| {
if data.starts_with(b"\x89PNG\r\n\x1a\n") {
Some(ImageKind::PNG(data))
} else if data.starts_with(&[0xff, 0xd8, 0xff]) {
Some(ImageKind::JPEG(data))
} else if data.starts_with(b"GIF87a") || data.starts_with(b"GIF89a") {
Some(ImageKind::GIF(data))
} else if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
Some(ImageKind::WEBP(data))
} else {
None
}
};
Options {
image_href_resolver: ImageHrefResolver {
resolve_string: Box::new(|_, _| None),
resolve_data: Box::new(move |mime, data, _| match mime {
"image/png" => Some(ImageKind::PNG(data)),
"image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),
"image/gif" => Some(ImageKind::GIF(data)),
"image/webp" => Some(ImageKind::WEBP(data)),
"text/plain" => raster(data),
_ => None,
}),
},
..Options::default()
}
}
/// Maximum nested XML container elements inside an SVG's root element (513 open elements in all,
/// matching Blink's 512-element HTML/SVG tree bound; Chromium's standalone XML limit of 5,000
/// exceeds both `usvg`'s 1,024 node cap and a worker stack at ~4.5 KiB per `<g>`).
#[cfg(feature = "svg")]
const MAX_SVG_DEPTH: usize = 512;
#[cfg(feature = "svg")]
fn svg_tree(bytes: &[u8]) -> Result<resvg::usvg::Tree, ImageError> {
use resvg::usvg;
const MAX_BYTES: usize = 32 << 20;
if bytes.len() > MAX_BYTES { return Err(ImageError("SVG is too large".into())); }
let unzipped;
let raw = if bytes.starts_with(&[0x1f, 0x8b]) {
unzipped = usvg::decompress_svgz(bytes).map_err(|e| ImageError(format!("SVG: {e}")))?;
if unzipped.len() > MAX_BYTES { return Err(ImageError("SVG is too large".into())); }
unzipped.as_slice()
} else {
bytes
};
let text = std::str::from_utf8(raw).map_err(|_| ImageError("SVG is not UTF-8".into()))?;
if svg_exceeds_depth(text, MAX_SVG_DEPTH) {
return Err(ImageError(format!("SVG exceeds maximum nesting depth of {MAX_SVG_DEPTH}")));
}
usvg::Tree::from_str(text, &svg_options()).map_err(|e| ImageError(format!("SVG: {e}")))
}
/// Iterative byte scan for open XML element depth, run before `roxmltree` so deeply nested input
/// cannot overflow the decoder stack inside the XML parser or `usvg`/`resvg`.
#[cfg(feature = "svg")]
fn svg_exceeds_depth(text: &str, max_nested: usize) -> bool {
let b = text.as_bytes();
let limit = max_nested + 1;
let (mut i, mut depth) = (0usize, 0usize);
while i < b.len() {
let Some(rel) = b[i..].iter().position(|&c| c == b'<') else { return false };
i += rel;
if b[i..].starts_with(b"<!--") {
i += 4;
let Some(end) = b[i..].windows(3).position(|w| w == b"-->") else { return false };
i += end + 3;
} else if b[i..].starts_with(b"<![CDATA[") {
i += 9;
let Some(end) = b[i..].windows(3).position(|w| w == b"]]>") else { return false };
i += end + 3;
} else if b[i..].starts_with(b"<?") {
i += 2;
let Some(end) = b[i..].windows(2).position(|w| w == b"?>") else { return false };
i += end + 2;
} else if b[i..].starts_with(b"<!") {
i += 2;
let (mut decl, mut quote) = (1usize, 0u8);
while i < b.len() && decl > 0 {
let c = b[i];
if quote != 0 {
if c == quote { quote = 0; }
} else if c == b'"' || c == b'\'' {
quote = c;
} else if c == b'<' {
decl += 1;
} else if c == b'>' {
decl -= 1;
}
i += 1;
}
} else if b[i..].starts_with(b"</") {
i += 2;
depth = depth.saturating_sub(1);
let mut quote = 0u8;
while i < b.len() {
let c = b[i];
i += 1;
if quote != 0 {
if c == quote { quote = 0; }
} else if c == b'"' || c == b'\'' {
quote = c;
} else if c == b'>' {
break;
}
}
} else {
i += 1;
let (mut quote, mut last_non_ws, mut closed) = (0u8, 0u8, false);
while i < b.len() {
let c = b[i];
i += 1;
if quote != 0 {
if c == quote { quote = 0; }
} else if c == b'"' || c == b'\'' {
quote = c;
last_non_ws = c;
} else if c == b'>' {
closed = true;
break;
} else if !c.is_ascii_whitespace() {
last_non_ws = c;
}
}
if !closed { return false; }
if last_non_ws != b'/' {
depth += 1;
if depth > limit { return true; }
}
}
}
false
}
#[cfg(feature = "svg")]
fn demultiply_rgba(pixmap: &resvg::tiny_skia::Pixmap) -> Vec<u8> {
pixmap.pixels().iter().flat_map(|p| {
let c = p.demultiply();
[c.red(), c.green(), c.blue(), c.alpha()]
}).collect()
}
/// An SVG scaled to fit `px` square, keeping its aspect ratio, as straight-alpha sRGB RGBA8.
/// `px == 0` rasterizes at twice the drawing's own size, at most 4096 pixels per side.
#[cfg(feature = "svg")]
#[doc(hidden)]
pub fn svg_rgba(bytes: &[u8], px: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
use resvg::tiny_skia;
let tree = svg_tree(bytes)?;
let size = tree.size();
let px = if px == 0 { (size.width().max(size.height()) * 2.0).ceil().clamp(1.0, 4096.0) as u32 } else { px };
let k = px as f32 / size.width().max(size.height());
let (w, h) = (((size.width() * k).round() as u32).clamp(1, px), ((size.height() * k).round() as u32).clamp(1, px));
let mut pixmap = tiny_skia::Pixmap::new(w, h).ok_or_else(|| ImageError("empty SVG".into()))?;
resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut());
Ok((w, h, demultiply_rgba(&pixmap)))
}
#[cfg(not(feature = "svg"))]
#[doc(hidden)]
pub fn svg_rgba(_: &[u8], _: u32) -> Result<(u32, u32, Vec<u8>), ImageError> {
Err(ImageError("SVG images need rune's `svg` feature".into()))
}
/// An SVG centre-cropped to fill `px` square (`object-fit: cover`), as straight-alpha sRGB RGBA8,
/// decoded through the same sandboxed `usvg` options as [`ImageCache`].
#[cfg(feature = "svg")]
pub fn svg_rgba_cover(bytes: &[u8], px: u32) -> Result<Vec<u8>, ImageError> {
use resvg::tiny_skia;
if px == 0 || px > 4096 { return Err(ImageError("invalid SVG raster size".into())); }
let tree = svg_tree(bytes)?;
let size = tree.size();
let k = px as f32 / size.width().min(size.height());
let t = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, (px as f32 - size.width() * k) / 2.0, (px as f32 - size.height() * k) / 2.0);
let mut pixmap = tiny_skia::Pixmap::new(px, px).ok_or_else(|| ImageError("empty SVG".into()))?;
resvg::render(&tree, t, &mut pixmap.as_mut());
Ok(demultiply_rgba(&pixmap))
}
#[cfg(not(feature = "svg"))]
pub fn svg_rgba_cover(_: &[u8], _: u32) -> Result<Vec<u8>, ImageError> {
Err(ImageError("SVG images need rune's `svg` feature".into()))
}
fn decode(bytes: &[u8]) -> Result<Decoded, ImageError> {
if is_svg(bytes) {
let (w, h, rgba) = svg_rgba(bytes, 0)?;
return mip_chain(w, h, &rgba);
}
if avif::is_avif(bytes) {
let (w, h, rgba) = avif::rgba(bytes)?;
return mip_chain(w, h, &rgba);
}
let bytes = if bytes.starts_with(b"icns") { icns_png(bytes)? } else { bytes };
if let Some(animation) = animated::decode(bytes) { return animation; }
use image::ImageDecoder;
let error = |e: image::ImageError| ImageError(e.to_string());
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format().map_err(|e| ImageError(e.to_string()))?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(256 * 1024 * 1024);
reader.limits(limits.clone());
// `ImageReader::decode`, keeping the decoder to read its EXIF orientation (a phone's JPEG
// stores its pixels as the sensor saw them and says how to turn them upright).
let mut decoder = reader.into_decoder().map_err(error)?;
limits.reserve(decoder.total_bytes()).map_err(error)?;
decoder.set_limits(limits).map_err(error)?;
let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
let mut image = image::DynamicImage::from_decoder(decoder).map_err(error)?;
image.apply_orientation(orientation);
let image = image.into_rgba8();
mip_chain(image.width(), image.height(), image.as_raw())
}
/// A PNG decoded to 8-bit RGBA by the PNG decoder alone. `image::load_from_memory_with_format`
/// dispatches on the format at run time, which links every codec the crate is built with (JPEG,
/// WebP, GIF, BMP, ICO) into an app that only ever reads PNGs from the clipboard or a cursor.
/// The same decoder and limits as that call's PNG arm.
#[doc(hidden)]
pub fn png_rgba8(bytes: &[u8]) -> image::ImageResult<image::RgbaImage> {
let decoder = image::codecs::png::PngDecoder::with_limits(std::io::Cursor::new(bytes), image::Limits::default())?;
Ok(image::DynamicImage::from_decoder(decoder)?.into_rgba8())
}
fn icns_png(bytes: &[u8]) -> Result<&[u8], ImageError> {
let invalid = || ImageError("invalid ICNS container or no supported PNG representation".into());
let len = u32::from_be_bytes(bytes.get(4..8).ok_or_else(invalid)?.try_into().unwrap()) as usize;
if len != bytes.len() { return Err(invalid()); }
let mut pos = 8;
let mut best = None;
let mut area = 0u64;
while pos < len {
let header = bytes.get(pos..pos + 8).ok_or_else(invalid)?;
let size = u32::from_be_bytes(header[4..8].try_into().unwrap()) as usize;
if size < 8 { return Err(invalid()); }
let end = pos.checked_add(size).filter(|end| *end <= len).ok_or_else(invalid)?;
let chunk = &bytes[pos + 8..end];
if chunk.starts_with(b"\x89PNG\r\n\x1a\n") && chunk.len() >= 24 {
let w = u32::from_be_bytes(chunk[16..20].try_into().unwrap());
let h = u32::from_be_bytes(chunk[20..24].try_into().unwrap());
let candidate = u64::from(w) * u64::from(h);
if w <= 8192 && h <= 8192 && candidate > area { best = Some(chunk); area = candidate; }
}
pos = end;
}
best.ok_or_else(invalid)
}
+145
View File
@@ -0,0 +1,145 @@
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
use super::*;
use rune_core::color::{srgb_decode, srgb_encode};
struct Counting;
thread_local! {
static LIVE: Cell<isize> = const { Cell::new(0) };
static PEAK: Cell<isize> = const { Cell::new(0) };
}
fn track(bytes: isize) {
LIVE.try_with(|live| {
live.set(live.get() + bytes);
PEAK.try_with(|peak| peak.set(peak.get().max(live.get()))).ok();
}).ok();
}
// SAFETY: forwards to the system allocator, counting live and peak bytes on this thread.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
track(l.size() as isize);
// SAFETY: delegates allocation with the caller's layout to `System`.
unsafe { System.alloc(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
track(-(l.size() as isize));
// SAFETY: delegates deallocation of `p` and `l` to `System`.
unsafe { System.dealloc(p, l) }
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
track(n as isize - l.size() as isize);
// SAFETY: delegates reallocation of `p`, `l` and `n` to `System`.
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static COUNTING: Counting = Counting;
fn peak<T>(f: impl FnOnce() -> T) -> (T, usize) {
let start = LIVE.with(Cell::get);
PEAK.with(|p| p.set(start));
let out = f();
(out, (PEAK.with(Cell::get) - start).max(0) as usize)
}
/// The float mip chain `mip_chain` replaced: every level kept as linear premultiplied `f32`s
/// at full size, encoded with `powf`.
fn reference(width: u32, height: u32, bytes: &[u8]) -> Vec<Mip> {
let mut linear: Vec<[f32; 4]> = bytes.as_chunks::<4>().0.iter().map(|p| {
let a = p[3] as f32 / 255.0;
[srgb_decode(p[0] as f32 / 255.0) * a, srgb_decode(p[1] as f32 / 255.0) * a, srgb_decode(p[2] as f32 / 255.0) * a, a]
}).collect();
let (mut w, mut h) = (width, height);
let mut mips = Vec::new();
loop {
let pixels = linear.iter().flat_map(|p| {
let a = byte(p[3]);
let rgb = [p[0], p[1], p[2]].map(|v| byte(srgb_encode(v.min(a as f32 / 255.0))));
[rgb[0], rgb[1], rgb[2], a]
}).collect();
mips.push(Mip { width: w, height: h, pixels });
if w == 1 && h == 1 { break; }
let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
let mut next = Vec::with_capacity((nw * nh) as usize);
for y in 0..nh { for x in 0..nw {
let (x0, x1) = (x as f32 * w as f32 / nw as f32, (x + 1) as f32 * w as f32 / nw as f32);
let (y0, y1) = (y as f32 * h as f32 / nh as f32, (y + 1) as f32 * h as f32 / nh as f32);
let mut sum = [0.0; 4];
for sy in y0.floor() as u32..(y1.ceil() as u32).min(h) {
for sx in x0.floor() as u32..(x1.ceil() as u32).min(w) {
let weight = ((sx + 1) as f32).min(x1) - (sx as f32).max(x0);
let weight = weight * (((sy + 1) as f32).min(y1) - (sy as f32).max(y0));
for c in 0..4 { sum[c] += linear[(sy * w + sx) as usize][c] * weight; }
}
}
next.push(sum.map(|v| v / ((x1 - x0) * (y1 - y0))));
}}
linear = next;
(w, h) = (nw, nh);
}
mips
}
/// Gradients, hashed noise and every alpha from clear to opaque, at odd and even sizes.
fn synthetic(w: u32, h: u32) -> Vec<u8> {
let mut out = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h { for x in 0..w {
let n = (x.wrapping_mul(0x9e37_79b9) ^ y.wrapping_mul(0x85eb_ca6b)).wrapping_mul(0xc2b2_ae35) >> 24;
let alpha = match (x / 7 + y / 5) % 5 { 0 => 255, 1 => 0, 2 => (x * 255 / w) as u8, 3 => n as u8, _ => 1 + (y % 3) as u8 };
out.extend_from_slice(&[(x * 255 / w) as u8, (y * 255 / h) as u8, n as u8, alpha]);
}}
out
}
#[test]
fn the_byte_mip_chain_matches_the_float_one_within_one_per_channel() {
for (w, h) in [(1, 1), (2, 1), (3, 1), (1, 7), (17, 9), (64, 64), (257, 131), (300, 1)] {
let src = synthetic(w, h);
let got = mip_chain(w, h, &src).unwrap().mips;
let want = reference(w, h, &src);
assert_eq!(got.len(), want.len(), "{w}x{h}: mip count");
for (level, (g, r)) in got.iter().zip(&want).enumerate() {
assert_eq!((g.width, g.height), (r.width, r.height), "{w}x{h} mip {level}: size");
let worst = g.pixels.iter().zip(&r.pixels).map(|(a, b)| a.abs_diff(*b)).max().unwrap();
assert!(worst <= 1, "{w}x{h} mip {level}: off by {worst}");
for (i, p) in g.pixels.as_chunks::<4>().0.iter().enumerate() {
assert!(p[..3].iter().all(|&c| c == 0) || p[3] > 0, "{w}x{h} mip {level} pixel {i}: light from a clear pixel");
}
}
let opaque = got[0].pixels.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).filter(|(_, s)| s[3] == 255);
assert!(opaque.into_iter().all(|(g, s)| g == s), "{w}x{h}: an opaque pixel passes through mip 0 unchanged");
}
}
/// The chain holds its output and nothing near a full-size float copy of the source.
#[test]
fn the_mip_chain_allocates_little_beyond_its_output() {
let (w, h) = (512, 256);
let src = synthetic(w, h);
let (mips, peak) = peak(|| mip_chain(w, h, &src).unwrap());
let output: usize = mips.mips.iter().map(|m| m.pixels.len()).sum();
assert!(peak < output + output / 8, "peak {peak} bytes for {output} bytes of mips");
}
/// Built a slice at a time, as on the browser's main thread, the chain is the same.
#[test]
fn a_mip_chain_built_in_slices_matches_one_built_whole() {
for (w, h) in [(1, 1), (3, 1), (17, 9), (64, 64), (257, 131)] {
let src = synthetic(w, h);
let whole = mip_chain(w, h, &src).unwrap().mips;
for budget in [1, 7, 100, 5000] {
let mut steps = mips::MipSteps::new(w, h, &src).unwrap();
let mut slices = 1;
while !steps.step(budget) { slices += 1; }
let sliced = steps.finish().mips;
assert_eq!(sliced.len(), whole.len(), "{w}x{h} by {budget}: mip count");
for (level, (s, o)) in sliced.iter().zip(&whole).enumerate() {
assert!((s.width, s.height, &s.pixels) == (o.width, o.height, &o.pixels), "{w}x{h} by {budget}: mip {level} differs");
}
if h >= 4 && budget == 1 { assert!(slices > 1, "{w}x{h}: one row per slice takes several"); }
}
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Linear-light mip chains, built whole on a cache worker or a slice at a time where the
//! same thread also draws frames (the browser's main thread), so it can stop between slices.
use super::{Decoded, ImageError, Mip};
pub(super) fn mip_chain(width: u32, height: u32, bytes: &[u8]) -> Result<Decoded, ImageError> {
let mut steps = MipSteps::new(width, height, bytes)?;
while !steps.step(usize::MAX) {}
Ok(steps.finish())
}
/// A mip chain under construction: mip 0 at once, then the smaller levels a slice of rows
/// at a time.
pub(super) struct MipSteps<'a> {
/// The straight-alpha source, which mip 1 filters.
source: &'a [u8],
mips: Vec<Mip>,
/// The level being built, and the row it continues from.
next: Vec<u8>,
row: u32,
}
impl<'a> MipSteps<'a> {
pub(super) fn new(width: u32, height: u32, bytes: &'a [u8]) -> Result<Self, ImageError> {
if width == 0 || height == 0 || width > 8192 || height > 8192
|| bytes.len() != width as usize * height as usize * 4
{ return Err(ImageError("RGBA image dimensions or byte length are invalid".into())); }
let srgb = &*SRGB;
// Mip 0 is the source with RGB premultiplied in linear light; an opaque pixel is unchanged.
let mut top = bytes.to_vec();
for p in top.as_chunks_mut::<4>().0 {
if p[3] == 255 { continue; }
let a = p[3] as f32 / 255.0;
for c in 0..3 { p[c] = srgb.encode(srgb.decode[p[c] as usize] * a, p[3]); }
}
Ok(MipSteps { source: bytes, mips: vec![Mip { width, height, pixels: top }], next: Vec::new(), row: 0 })
}
/// Build at most about `budget` more pixels (whole rows, at least one); true once the
/// chain reaches 1×1.
pub(super) fn step(&mut self, mut budget: usize) -> bool {
let srgb = &*SRGB;
loop {
let last = self.mips.last().expect("mip 0 is built first");
let (w, h) = (last.width, last.height);
if w == 1 && h == 1 { return true; }
if budget == 0 { return false; }
let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
if self.row == 0 { self.next.reserve_exact(nw as usize * nh as usize * 4); }
let rows = (budget / nw as usize).clamp(1, (nh - self.row) as usize) as u32;
let range = self.row..self.row + rows;
// Mip 1 filters the straight source, so a translucent edge is premultiplied once,
// not quantized first. Each later mip filters the bytes of the one above it.
if self.mips.len() == 1 {
downsample_rows(w, h, self.source, range, &mut self.next, |p| {
let a = p[3] as f32 / 255.0;
[srgb.decode[p[0] as usize] * a, srgb.decode[p[1] as usize] * a, srgb.decode[p[2] as usize] * a, a]
});
} else {
downsample_rows(w, h, &last.pixels, range, &mut self.next, |p| {
[srgb.decode[p[0] as usize], srgb.decode[p[1] as usize], srgb.decode[p[2] as usize], p[3] as f32 / 255.0]
});
}
self.row += rows;
budget = budget.saturating_sub(rows as usize * nw as usize);
if self.row == nh {
self.mips.push(Mip { width: nw, height: nh, pixels: std::mem::take(&mut self.next) });
self.row = 0;
}
}
}
pub(super) fn finish(self) -> Decoded { Decoded { mips: self.mips, motion: None } }
}
/// Rows `rows` of `w`×`h` RGBA8 `src` halved by area, appended to `out`, summing `linear`
/// (premultiplied linear RGBA) of each source pixel. Area resampling includes the last
/// row/column of odd-sized sources.
fn downsample_rows(w: u32, h: u32, src: &[u8], rows: std::ops::Range<u32>, out: &mut Vec<u8>, linear: impl Fn(&[u8; 4]) -> [f32; 4]) {
let src = src.as_chunks::<4>().0;
let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
let mut emit = |sum: [f32; 4], area: f32| {
let [r, g, b, a] = sum.map(|v| v / area);
let a = byte(a);
out.extend_from_slice(&[SRGB.encode(r, a), SRGB.encode(g, a), SRGB.encode(b, a), a]);
};
if w % 2 == 0 && h % 2 == 0 {
// Each target pixel is exactly a 2×2 block.
let w = w as usize;
for y in rows.start as usize..rows.end as usize { for x in 0..nw as usize {
let i = 2 * y * w + 2 * x;
let mut sum = [0.0; 4];
for p in [i, i + 1, i + w, i + w + 1].map(|i| linear(&src[i])) {
for c in 0..4 { sum[c] += p[c]; }
}
emit(sum, 4.0);
}}
return;
}
for y in rows { for x in 0..nw {
let (x0, x1) = (x as f32 * w as f32 / nw as f32, (x + 1) as f32 * w as f32 / nw as f32);
let (y0, y1) = (y as f32 * h as f32 / nh as f32, (y + 1) as f32 * h as f32 / nh as f32);
let mut sum = [0.0; 4];
for sy in y0.floor() as u32..(y1.ceil() as u32).min(h) {
for sx in x0.floor() as u32..(x1.ceil() as u32).min(w) {
let weight = ((sx + 1) as f32).min(x1) - (sx as f32).max(x0);
let weight = weight * (((sy + 1) as f32).min(y1) - (sy as f32).max(y0));
let p = linear(&src[(sy * w + sx) as usize]);
for c in 0..4 { sum[c] += p[c] * weight; }
}
}
emit(sum, (x1 - x0) * (y1 - y0));
}}
}
pub(super) fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 }
/// sRGB transfer tables, so mip generation runs no `powf` per pixel.
struct Srgb {
/// Linear light of each sRGB byte.
decode: [f32; 256],
/// `up[k]`: the linear value at and above which the sRGB encoding rounds past byte `k`.
up: [f32; 256],
/// The byte at the low edge of each 1/`STEPS` of linear light. The curve's steepest
/// slope (12.92) crosses under one byte per step, so one `up` comparison finishes it.
coarse: [u8; STEPS + 1],
}
const STEPS: usize = 4096;
static SRGB: std::sync::LazyLock<Srgb> = std::sync::LazyLock::new(|| {
let mut up: [f32; 256] = std::array::from_fn(|k| rune_core::color::srgb_decode((k as f32 + 0.5) / 255.0));
up[255] = f32::INFINITY;
Srgb {
decode: std::array::from_fn(|i| rune_core::color::srgb_decode(i as f32 / 255.0)),
coarse: std::array::from_fn(|i| up.partition_point(|&t| t <= i as f32 / STEPS as f32) as u8),
up,
}
});
impl Srgb {
/// The sRGB byte of premultiplied linear `v`, capped by its quantized alpha `a` so a pixel
/// whose alpha rounded to zero emits no light.
fn encode(&self, v: f32, a: u8) -> u8 {
let v = v.clamp(0.0, a as f32 / 255.0);
let b = self.coarse[(v * STEPS as f32) as usize];
b + u8::from(v >= self.up[b as usize])
}
}
+446
View File
@@ -0,0 +1,446 @@
//! Pixel buffers an app replaces at will (a CPU-shaded HUD frame, a video frame), drawn by
//! `El::pixels`. Each runtime keeps a CPU-side RGBA atlas the renderer uploads by dirty rows,
//! like the glyph atlas, allocated only once an element shows pixels.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use crate::place::{SurfaceFit, SurfacePlace};
pub const IMAGE_ATLAS_SIZE: u32 = 1024;
/// Rows a shelf page starts with (`ImagePage::new`).
const IMAGE_PAGE_START_ROWS: u32 = 128;
struct Frame {
width: u32,
height: u32,
rgba: Vec<u8>,
generation: u64,
mips: Option<Arc<crate::Decoded>>,
}
/// A replaceable RGBA image, shared between the producer and the view. Clone it freely.
#[derive(Clone)]
pub struct Pixels {
id: u64,
frame: Arc<Mutex<Frame>>,
/// Wakes the windows and overlays whose scene shows this image.
#[doc(hidden)]
pub source: Arc<rune_core::live::Source>,
/// The URL or path an `ImageCache` loaded it from.
url: Option<Arc<str>>,
/// The candidates `ImageCache::url_set` chose `url` from, as an HTML `srcset`.
srcset: Option<Arc<str>>,
/// The `ImageCache` entry these pixels came from, so the cache still finds it while
/// anything draws them, and a view that asks for the image again on its next build gets it
/// back instead of fetching it anew.
keep: Option<Arc<dyn std::any::Any + Send + Sync>>,
}
impl std::fmt::Debug for Pixels {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let frame = self.frame.lock().unwrap();
write!(f, "Pixels({}, {}x{}, gen {})", self.id, frame.width, frame.height, frame.generation)
}
}
impl Default for Pixels {
fn default() -> Self {
Self::new()
}
}
impl Pixels {
pub fn new() -> Pixels {
static NEXT: AtomicU64 = AtomicU64::new(1);
Pixels {
id: NEXT.fetch_add(1, Ordering::Relaxed),
frame: Arc::new(Mutex::new(Frame { width: 0, height: 0, rgba: Vec::new(), generation: 0, mips: None })),
source: rune_core::live::Source::new(0),
url: None,
srcset: None,
keep: None,
}
}
pub(crate) fn from_url(url: Option<Arc<str>>, srcset: Option<Arc<str>>) -> Pixels {
Pixels { url, srcset, ..Pixels::new() }
}
pub(crate) fn keeping(mut self, keep: Arc<dyn std::any::Any + Send + Sync>) -> Pixels {
self.keep = Some(keep);
self
}
/// The URL ([`ImageCache::url`](crate::ImageCache::url)) or path
/// ([`ImageCache::file`](crate::ImageCache::file)) the image was loaded from, as given, so
/// a page export can point an `<img>` at it.
pub fn source_url(&self) -> Option<&str> {
self.url.as_deref()
}
/// For an image from [`ImageCache::url_set`](crate::ImageCache::url_set), every size it
/// chose from, as an HTML `srcset` (`"a-640.avif 640w, a-1280.avif 1280w"`).
pub fn source_set(&self) -> Option<&str> {
self.srcset.as_deref()
}
/// Replaces the image: `rgba` is `width * height` straight-alpha sRGB pixels, rows top
/// first. Call it from any thread: it wakes only the windows and overlays showing the
/// image, and their next frame uploads it. Sets between two frames coalesce into one wake
/// and one upload of the latest image; a hidden or covered window catches up when it shows
/// again. This is the streaming path: no decoding or mip generation, and a same-size
/// frame reuses its atlas slot.
pub fn set(&self, width: u32, height: u32, rgba: Vec<u8>) {
assert_eq!(Some(rgba.len()), (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4)), "rgba must hold width * height pixels");
{
let mut frame = self.frame.lock().unwrap();
frame.width = width;
frame.height = height;
frame.rgba = rgba;
frame.generation += 1;
frame.mips = None;
}
self.source.notify();
}
pub(crate) fn set_mips(&self, mips: Arc<crate::Decoded>) {
{
let mut frame = self.frame.lock().unwrap();
frame.width = mips.mips[0].width;
frame.height = mips.mips[0].height;
frame.rgba.clear();
frame.mips = Some(mips);
frame.generation += 1;
}
self.source.notify();
}
pub fn size(&self) -> (u32, u32) {
let frame = self.frame.lock().unwrap();
(frame.width, frame.height)
}
#[doc(hidden)]
pub fn signature(&self) -> (u64, u64) {
let frame = self.frame.lock().unwrap();
(self.id, frame.generation)
}
/// The image's RGBA bytes as [`Pixels::set`] gave them (empty for a decoded image's mips).
#[doc(hidden)]
pub fn rgba(&self) -> Vec<u8> {
self.frame.lock().unwrap().rgba.clone()
}
}
/// Where an image of `size` texels draws in `rect` ([x, y, w, h], device pixels) and which window
/// of it shows, as fractions [x0, y0, x1, y1]. `None` stretches; `Fit` letterboxes (on whole
/// pixels at unscaled rest, continuous while scaled); `Fill` keeps the rect and crops the
/// overflow. Spare space and overflow split by `place`'s anchor (centred by default); an unscaled
/// place draws one texel per pixel and crops or leaves the rest empty.
#[doc(hidden)]
pub fn fit(
fit: Option<SurfaceFit>,
place: SurfacePlace,
rect: [f32; 4],
size: (u32, u32),
) -> ([f32; 4], [f32; 4]) {
fit_in(fit, place, rect, size, 1.0)
}
#[doc(hidden)]
pub fn fit_in(
fit: Option<SurfaceFit>,
place: SurfacePlace,
rect: [f32; 4],
size: (u32, u32),
snap_weight: f32,
) -> ([f32; 4], [f32; 4]) {
let whole = [0.0, 0.0, 1.0, 1.0];
let [x, y, w, h] = rect;
let (iw, ih) = (size.0 as f32, size.1 as f32);
if fit.is_none() || iw <= 0.0 || ih <= 0.0 || w <= 0.0 || h <= 0.0 { return (rect, whole); }
let [kx, ky] = place.share();
let u = if (w - w.round()).abs() < 1.0 / 512.0 && (h - h.round()).abs() < 1.0 / 512.0 {
snap_weight.clamp(0.0, 1.0)
} else {
0.0
};
let blend = |exact: [f32; 4], snapped: [f32; 4]| {
if u <= 0.0 {
exact
} else if u >= 1.0 {
snapped
} else {
std::array::from_fn(|i| exact[i] + (snapped[i] - exact[i]) * u)
}
};
if place.unscaled {
let (dw, dh) = (iw.min(w), ih.min(h));
let (sx, sy) = (dw / iw, dh / ih);
let ((x0, x1), (y0, y1)) = (window(sx, kx), window(sy, ky));
let exact = [x + (w - dw) * kx, y + (h - dh) * ky, dw, dh];
let snapped = [x + ((w - dw) * kx).round(), y + ((h - dh) * ky).round(), dw, dh];
return (blend(exact, snapped), [x0, y0, x1, y1]);
}
if fit == Some(SurfaceFit::Fit) {
let k = (w / iw).min(h / ih);
let (dw, dh) = ((iw * k).clamp(1.0, w), (ih * k).clamp(1.0, h));
let exact = [x + (w - dw) * kx, y + (h - dh) * ky, dw, dh];
if u <= 0.0 {
return (exact, whole);
}
let (sw, sh) = ((iw * k).round().clamp(1.0, w), (ih * k).round().clamp(1.0, h));
let snapped = [x + ((w - sw) * kx).round(), y + ((h - sh) * ky).round(), sw, sh];
return (blend(exact, snapped), whole);
}
let k = (w / iw).max(h / ih);
let (sx, sy) = (w / (iw * k), h / (ih * k));
let ((x0, x1), (y0, y1)) = (window(sx, kx), window(sy, ky));
(rect, [x0, y0, x1, y1])
}
/// The visible fraction `[a, b]` of an axis when `span` of it shows and `share` of the hidden part lies before.
fn window(span: f32, share: f32) -> (f32, f32) {
if share == 0.5 { return ((1.0 - span) * 0.5, (1.0 + span) * 0.5); }
let a = (1.0 - span) * share;
(a, a + span)
}
struct Slot {
page: usize,
x: u32,
y: u32,
w: u32,
h: u32,
generation: u64,
/// The animation frame copied in.
frame: usize,
}
/// One stable shelf page, or an exact-size standalone page for a large image.
pub struct ImagePage {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
/// Rows `[y0, y1)` changed since the last upload.
pub dirty: Option<(u32, u32)>,
shelf_x: u32,
shelf_y: u32,
shelf_h: u32,
/// Drawn from in the last completed frame.
shown: bool,
/// Drawn from in this frame so far; only ever set until the frame ends.
touched: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Placed {
pub rect: [u32; 4],
pub page: usize,
pub premultiplied: bool,
}
/// Streaming buffers keep one slot. Static images keep a slot per sampled mip level.
#[derive(Default)]
pub struct ImageAtlas {
pub pages: Vec<ImagePage>,
slots: HashMap<(u64, usize), Slot>,
/// When each animated image drawn here started playing, on the animation clock: its first
/// draw, kept while the atlas holds it.
starts: HashMap<u64, f64>,
/// Frames copied in so far, so the idle meter sees new pixels in a slot it already drew.
#[cfg(debug_assertions)]
#[doc(hidden)]
pub copies: u64,
}
impl ImageAtlas {
/// The atlas origin and size of `pixels`, copying a new frame in when it changed. None while
/// it's empty or doesn't fit.
pub fn place(&mut self, pixels: &Pixels, drawn: [f32; 2]) -> Option<Placed> {
self.place_at(pixels, drawn, None).map(|(placed, _)| placed)
}
/// [`Self::place`] at `now` on the animation clock: an animated image shows the frame for
/// the time since it was first drawn here, and says when (on the same clock) the next one
/// shows, or `None` for a still or an animation that has stopped. `None` for `now` shows
/// an animation's first frame.
#[doc(hidden)]
pub fn place_at(&mut self, pixels: &Pixels, drawn: [f32; 2], now: Option<f64>) -> Option<(Placed, Option<f64>)> {
let frame = pixels.frame.lock().unwrap();
let (mut w, mut h) = (frame.width, frame.height);
if w == 0 || h == 0 || w > 8192 || h > 8192 {
return None;
}
let mut level = 0;
let mut shown = 0;
let mut next = None;
let bytes = if let Some(decoded) = &frame.mips {
let mips = match (&decoded.motion, now) {
(Some(motion), Some(now)) => {
let start = *self.starts.entry(pixels.id).or_insert(now);
let (i, change) = motion.at(now - start);
(shown, next) = (i, change.map(|t| start + t));
motion.frame(&decoded.mips, i)
}
_ => &decoded.mips[..],
};
// Choose the smallest prefiltered level that still covers both device-pixel axes.
// No mip construction or resampling happens on the render thread.
while let Some(next) = mips.get(level + 1) {
if (next.width as f32) < drawn[0].clamp(1.0, frame.width as f32)
|| (next.height as f32) < drawn[1].clamp(1.0, frame.height as f32) { break; }
level += 1;
}
let mip = &mips[level];
(w, h) = (mip.width, mip.height);
&mip.pixels
} else { &frame.rgba };
let key = (pixels.id, level);
if self.slots.get(&key).is_some_and(|s| s.w != w || s.h != h) {
self.slots.remove(&key);
}
if !self.slots.contains_key(&key) {
let (page, x, y) = self.allocate(w, h);
self.slots.insert(key, Slot { page, x, y, w, h, generation: 0, frame: 0 });
}
let slot = self.slots.get_mut(&key).unwrap();
self.pages[slot.page].touched = true;
if slot.generation != frame.generation || slot.frame != shown {
slot.generation = frame.generation;
slot.frame = shown;
#[cfg(debug_assertions)]
{ self.copies += 1; }
let page = &mut self.pages[slot.page];
let row = (page.width * 4) as usize;
for line in 0..h as usize {
let dst = (slot.y as usize + line) * row + slot.x as usize * 4;
let src = line * w as usize * 4;
page.data[dst..dst + w as usize * 4].copy_from_slice(&bytes[src..src + w as usize * 4]);
}
let (y0, y1) = (slot.y, slot.y + h);
page.dirty = Some(page.dirty.map_or((y0, y1), |(a, b)| (a.min(y0), b.max(y1))));
}
Some((Placed { rect: [slot.x, slot.y, w, h], page: slot.page, premultiplied: frame.mips.is_some() }, next))
}
/// Whether the atlas currently holds a slot for `pixels` at mip `level`.
#[doc(hidden)]
pub fn has_slot(&self, pixels: &Pixels, level: usize) -> bool {
self.slots.contains_key(&(pixels.id, level))
}
/// Forgets images no element showed since the last call, except on pages that still show
/// one and on the first page: shelves never reuse a slot's space until their page starts
/// over, so an image shown again there (a view come back to) needs no copy or upload. A
/// page left with nothing starts over so replaced sizes don't fill the atlas; a full atlas
/// starts over a page that showed nothing last frame or yet this one before it adds one.
pub fn end_frame(&mut self) {
let pages = &self.pages;
let first_kept = pages.first().is_some_and(|p| p.width <= IMAGE_ATLAS_SIZE && p.height <= IMAGE_ATLAS_SIZE);
self.slots.retain(|_, s| pages[s.page].touched || (s.page == 0 && first_kept));
if !self.starts.is_empty() {
let slots = &self.slots;
self.starts.retain(|id, _| slots.keys().any(|(slot, _)| slot == id));
}
for (i, page) in self.pages.iter_mut().enumerate() {
page.shown = std::mem::take(&mut page.touched);
if !self.slots.values().any(|slot| slot.page == i) {
(page.shelf_x, page.shelf_y, page.shelf_h) = (0, 0, 0);
page.dirty = None;
if page.width > IMAGE_ATLAS_SIZE || page.height > IMAGE_ATLAS_SIZE {
page.data = Vec::new();
}
}
}
let keep = self.slots.values().map(|s| s.page + 1).max().unwrap_or(0);
self.pages.truncate(keep);
}
/// A window at rest (`window::rest`): forgets the images no element showed in the last
/// frame, the first page's included, and frees the CPU copy of every page left empty. An
/// image shown again after it is copied in again.
pub fn rest(&mut self) {
let pages = &self.pages;
self.slots.retain(|_, s| pages[s.page].shown);
let slots = &self.slots;
self.starts.retain(|id, _| slots.keys().any(|(slot, _)| slot == id));
for (i, page) in self.pages.iter_mut().enumerate() {
if !self.slots.values().any(|slot| slot.page == i) {
(page.shelf_x, page.shelf_y, page.shelf_h) = (0, 0, 0);
page.dirty = None;
page.data = Vec::new();
}
}
let keep = self.slots.values().map(|s| s.page + 1).max().unwrap_or(0);
self.pages.truncate(keep);
}
/// Marks every row for upload (a new texture).
pub fn invalidate(&mut self) {
for page in &mut self.pages { page.dirty = Some((0, page.height)); }
}
fn allocate(&mut self, w: u32, h: u32) -> (usize, u32, u32) {
for (i, page) in self.pages.iter_mut().enumerate() {
if page.data.is_empty() { *page = ImagePage::new(w, h); }
if let Some((x, y)) = page.allocate(w, h) { return (i, x, y); }
}
// Full: start over a shelf page that showed nothing last frame or yet this one. A page
// not drawn from yet this frame may still be, later in the tree.
let idle = |p: &ImagePage| !p.shown && !p.touched && p.width <= IMAGE_ATLAS_SIZE && p.height <= IMAGE_ATLAS_SIZE
&& p.shelf_y + p.shelf_h > 0;
if w <= IMAGE_ATLAS_SIZE && h <= IMAGE_ATLAS_SIZE && let Some(i) = self.pages.iter().position(idle) {
self.slots.retain(|_, s| s.page != i);
let page = &mut self.pages[i];
(page.shelf_x, page.shelf_y, page.shelf_h) = (0, 0, 0);
let (x, y) = page.allocate(w, h).unwrap();
return (i, x, y);
}
let mut page = ImagePage::new(w, h);
let (x, y) = page.allocate(w, h).unwrap();
self.pages.push(page);
(self.pages.len() - 1, x, y)
}
}
impl ImagePage {
/// A shelf page starts with the rows its first image needs (at least
/// `IMAGE_PAGE_START_ROWS`) and grows as its shelves fill (`allocate`), up to
/// `IMAGE_ATLAS_SIZE`: a window that shows a few icons holds 512 KiB of it, not 4 MiB.
fn new(w: u32, h: u32) -> Self {
let (width, height) = if w > IMAGE_ATLAS_SIZE || h > IMAGE_ATLAS_SIZE { (w, h) }
else { (IMAGE_ATLAS_SIZE, h.next_power_of_two().max(IMAGE_PAGE_START_ROWS)) };
Self { width, height, data: vec![0; width as usize * height as usize * 4],
dirty: None, shelf_x: 0, shelf_y: 0, shelf_h: 0, shown: false, touched: false }
}
fn allocate(&mut self, w: u32, h: u32) -> Option<(u32, u32)> {
let shelf = self.width == IMAGE_ATLAS_SIZE && self.height <= IMAGE_ATLAS_SIZE;
if w > self.width || h > if shelf { IMAGE_ATLAS_SIZE } else { self.height } { return None; }
if self.shelf_x + w > self.width {
self.shelf_y += self.shelf_h;
self.shelf_x = 0;
self.shelf_h = 0;
}
if self.shelf_y + h > self.height {
if !shelf || self.shelf_y + h > IMAGE_ATLAS_SIZE { return None; }
// Rows already placed keep their texels; the renderer makes the page's texture again
// at its new size and uploads all of it.
self.height = (self.shelf_y + h).next_power_of_two().min(IMAGE_ATLAS_SIZE);
self.data.resize(self.width as usize * self.height as usize * 4, 0);
self.dirty = Some((0, self.height));
}
let at = (self.shelf_x, self.shelf_y);
self.shelf_x += w;
self.shelf_h = self.shelf_h.max(h);
Some(at)
}
}
#[cfg(test)]
#[path = "pixels_tests.rs"]
mod tests;
+172
View File
@@ -0,0 +1,172 @@
use super::*;
#[test]
#[ignore = "manual staging benchmark; reports measurements, not a timing threshold"]
fn image_staging_costs() {
use std::hint::black_box;
let stream = Pixels::new();
stream.set(224, 128, vec![0; 224 * 128 * 4]);
let mut atlas = ImageAtlas::default();
atlas.place(&stream, [224.0, 128.0]);
atlas.end_frame();
atlas.pages[0].dirty = None;
let buffers: Vec<_> = (0..120).map(|_| vec![128; 224 * 128 * 4]).collect();
let start = rune_core::time::now();
let mut upload_bytes = 0u64;
for bytes in buffers {
stream.set(224, 128, bytes);
black_box(atlas.place(&stream, [224.0, 128.0]));
atlas.end_frame();
let page = &mut atlas.pages[0];
let (lo, hi) = page.dirty.take().unwrap();
upload_bytes += u64::from((hi - lo) * page.width * 4);
}
eprintln!("stream 224x128: {:.1} us/stage, {} upload bytes/frame, {} page", start.elapsed().as_secs_f64() * 1e6 / 120.0, upload_bytes / 120, atlas.pages.len());
let cache = crate::ImageCache::new(Arc::new(|| {}));
let icons: Vec<_> = (0..100).map(|i| cache.rgba(128, 128, [i, 50, 100, 255].repeat(128 * 128))).collect();
for icon in &icons { icon.wait().unwrap(); }
let mut atlas = ImageAtlas::default();
for icon in &icons { atlas.place(icon.pixels(), [32.0; 2]); }
atlas.end_frame();
for page in &mut atlas.pages { page.dirty = None; }
let start = rune_core::time::now();
for _ in 0..120 {
for icon in &icons { black_box(atlas.place(icon.pixels(), [32.0; 2])); }
atlas.end_frame();
}
eprintln!("100 static 128->32 icons: {:.1} us/frame, {} pages, {} dirty pages", start.elapsed().as_secs_f64() * 1e6 / 120.0, atlas.pages.len(), atlas.pages.iter().filter(|p| p.dirty.is_some()).count());
}
#[test]
fn fit_letterboxes_on_whole_pixels_and_fill_crops_the_centre() {
use SurfaceFit::{Fill, Fit};
const C: SurfacePlace = SurfacePlace::CENTRED;
let rect = [10.0, 20.0, 40.0, 40.0];
assert_eq!(fit(None, C, rect, (80, 20)), (rect, [0.0, 0.0, 1.0, 1.0]));
assert_eq!(fit(Some(Fit), C, rect, (80, 20)), ([10.0, 35.0, 40.0, 10.0], [0.0, 0.0, 1.0, 1.0]));
assert_eq!(fit(Some(Fit), C, rect, (20, 80)).0, [25.0, 20.0, 10.0, 40.0]);
assert_eq!(fit(Some(Fill), C, rect, (80, 20)), (rect, [0.375, 0.0, 0.625, 1.0]));
assert_eq!(fit(Some(Fill), C, rect, (40, 40)), (rect, [0.0, 0.0, 1.0, 1.0]));
assert_eq!(fit(Some(Fit), C, rect, (0, 0)).0, rect, "an empty image keeps the rect");
}
#[test]
fn frames_copy_in_once_per_generation_and_resize_moves_the_slot() {
let mut atlas = ImageAtlas::default();
let px = Pixels::new();
assert_eq!(atlas.place(&px, [2.0, 1.0]), None, "empty images draw nothing");
px.set(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 128]);
assert_eq!(atlas.place(&px, [2.0, 1.0]).unwrap().rect, [0, 0, 2, 1]);
assert_eq!(atlas.pages[0].dirty.take(), Some((0, 1)));
assert_eq!(&atlas.pages[0].data[..8], &[255, 0, 0, 255, 0, 255, 0, 128]);
atlas.place(&px, [2.0, 1.0]);
assert_eq!(atlas.pages[0].dirty, None, "an unchanged frame uploads nothing");
px.set(3, 2, vec![7; 24]);
let [x, y, w, h] = atlas.place(&px, [3.0, 2.0]).unwrap().rect;
assert_eq!((w, h), (3, 2));
assert_eq!(atlas.pages[0].data[((y * IMAGE_ATLAS_SIZE + x) * 4) as usize], 7);
let other = Pixels::new();
other.set(1, 1, vec![1; 4]);
atlas.place(&other, [1.0, 1.0]);
atlas.end_frame();
atlas.place(&px, [3.0, 2.0]);
atlas.end_frame();
assert!(atlas.slots.contains_key(&(px.id, 0)) && atlas.slots.contains_key(&(other.id, 0)), "the first page keeps unshown images");
}
#[test]
fn an_image_shown_again_after_a_while_is_not_copied_again() {
let mut atlas = ImageAtlas::default();
let (list, grid) = (Pixels::new(), Pixels::new());
list.set(32, 32, vec![1; 32 * 32 * 4]);
grid.set(48, 48, vec![2; 48 * 48 * 4]);
let shown = atlas.place(&list, [32.0; 2]).unwrap();
atlas.end_frame();
for _ in 0..4 {
atlas.place(&grid, [48.0; 2]);
atlas.end_frame();
}
atlas.pages[0].dirty = None;
assert_eq!(atlas.place(&list, [32.0; 2]), Some(shown));
assert_eq!(atlas.pages[0].dirty, None, "no copy, no upload");
}
#[test]
fn a_full_atlas_starts_over_pages_that_show_nothing_before_it_grows() {
let mut atlas = ImageAtlas::default();
let old: Vec<Pixels> = (0..4).map(|_| { let p = Pixels::new(); p.set(512, 512, vec![1; 512 * 512 * 4]); p }).collect();
for p in &old { atlas.place(p, [512.0; 2]); }
atlas.end_frame();
atlas.end_frame();
assert_eq!(atlas.pages.len(), 1);
let new = Pixels::new();
new.set(512, 512, vec![2; 512 * 512 * 4]);
assert_eq!(atlas.place(&new, [512.0; 2]).unwrap().rect, [0, 0, 512, 512]);
assert_eq!(atlas.pages.len(), 1);
assert!(!atlas.slots.contains_key(&(old[0].id, 0)), "the page's old images are forgotten");
}
/// A new image earlier in the tree than a body that fills the first page: the body isn't
/// drawn yet this frame when the new image needs room.
#[test]
fn a_full_page_shown_last_frame_is_not_started_over_before_its_images_are_drawn() {
let mut atlas = ImageAtlas::default();
let body: Vec<Pixels> = (0..4).map(|i| { let p = Pixels::new(); p.set(512, 512, vec![i; 512 * 512 * 4]); p }).collect();
let placed: Vec<_> = body.iter().map(|p| atlas.place(p, [512.0; 2]).unwrap()).collect();
atlas.end_frame();
atlas.pages[0].dirty = None;
let new = Pixels::new();
new.set(64, 64, vec![9; 64 * 64 * 4]);
assert_eq!(atlas.place(&new, [64.0; 2]).unwrap().page, 1);
assert_eq!(body.iter().map(|p| atlas.place(p, [512.0; 2]).unwrap()).collect::<Vec<_>>(), placed);
assert_eq!(atlas.pages[0].dirty, None, "the body copies in nothing");
}
/// An image drawn twice in a frame, resized by its producer in between: the first draw's
/// pixels stay put while this frame still samples them.
#[test]
fn an_image_resized_between_two_draws_keeps_the_first_draws_pixels() {
let mut atlas = ImageAtlas::default();
let px = Pixels::new();
px.set(512, 512, vec![1; 512 * 512 * 4]);
let fill: Vec<Pixels> = (0..3).map(|_| { let p = Pixels::new(); p.set(512, 512, vec![2; 512 * 512 * 4]); p }).collect();
atlas.place(&px, [512.0; 2]);
for p in &fill { atlas.place(p, [512.0; 2]); }
atlas.end_frame();
let first = atlas.place(&px, [512.0; 2]).unwrap();
px.set(600, 600, vec![3; 600 * 600 * 4]);
let second = atlas.place(&px, [600.0; 2]).unwrap();
assert_ne!(second.page, first.page);
let [x, y, ..] = first.rect;
assert_eq!(atlas.pages[first.page].data[((y * IMAGE_ATLAS_SIZE + x) * 4) as usize], 1);
}
#[test]
fn pages_expand_reclaim_and_keep_streaming_slots_stable() {
let mut atlas = ImageAtlas::default();
let stream = Pixels::new();
stream.set(224, 128, vec![1; 224 * 128 * 4]);
let first = atlas.place(&stream, [112.0, 64.0]).unwrap();
assert!(!first.premultiplied);
let large = Pixels::new();
large.set(2048, 1, vec![2; 2048 * 4]);
let second = atlas.place(&large, [2048.0, 1.0]).unwrap();
assert_ne!(first.page, second.page);
assert_eq!((atlas.pages[second.page].width, atlas.pages[second.page].height), (2048, 1));
let full = Pixels::new();
full.set(1024, 1024, vec![3; 1024 * 1024 * 4]);
let third = atlas.place(&full, [1024.0; 2]).unwrap();
assert_eq!(third.page, 2);
atlas.end_frame();
stream.set(224, 128, vec![4; 224 * 128 * 4]);
assert_eq!(atlas.place(&stream, [112.0, 64.0]).unwrap(), first);
atlas.place(&full, [1024.0; 2]);
atlas.end_frame();
assert_eq!(atlas.pages.len(), 3);
assert!(atlas.pages[second.page].data.is_empty(), "unused middle standalone page releases storage");
assert_eq!(atlas.place(&stream, [112.0, 64.0]).unwrap(), first);
atlas.end_frame();
assert_eq!(atlas.pages.len(), 1, "unused trailing pages release their storage");
atlas.end_frame();
assert_eq!(atlas.pages.len(), 1, "the first page keeps its images");
}
+64
View File
@@ -0,0 +1,64 @@
//! Alignment and aspect-preserving placement for surfaces and pixel buffers: which edge a spare
//! or cropped side is shared from, and whether the frame is scaled at all.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum Align {
#[default]
Start,
Center,
End,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SurfaceFit {
#[default]
Fit,
Fill,
}
/// `El::surface_anchor` and `El::surface_unscaled`. The default centres and scales by `SurfaceFit`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SurfacePlace {
pub anchor: [Align; 2],
pub unscaled: bool,
}
impl SurfacePlace {
pub const CENTRED: SurfacePlace = SurfacePlace { anchor: [Align::Center; 2], unscaled: false };
}
impl Default for SurfacePlace {
fn default() -> Self { Self::CENTRED }
}
impl SurfacePlace {
/// How much of the spare (or cropped) space along each axis lies before the image.
pub fn share(self) -> [f32; 2] {
self.anchor.map(|a| match a {
Align::Start => 0.0,
Align::Center => 0.5,
Align::End => 1.0,
})
}
}
/// The image's rect in device pixels inside `node` ([x, y, w, h]); it may overflow the node, which
/// then crops it. `unscaled` draws one texel per device pixel and ignores `fit`.
pub fn image_rect(node: [f32; 4], source: [u32; 2], fit: SurfaceFit, place: SurfacePlace) -> [f32; 4] {
let (sw, sh) = (source[0] as f32, source[1] as f32);
let scale = if place.unscaled {
1.0
} else {
let (a, b) = (node[2] / sw, node[3] / sh);
match fit {
SurfaceFit::Fit => a.min(b),
SurfaceFit::Fill => a.max(b),
}
};
let [kx, ky] = place.share();
let (w, h) = (sw * scale, sh * scale);
let x = node[0] + (node[2] - w) * kx;
let y = node[1] + (node[3] - h) * ky;
// At unit scale favour sharp shared text over a subpixel translation of its image.
if (scale - 1.0).abs() < 1e-6 { [x.round(), y.round(), w, h] } else { [x, y, w, h] }
}
+331
View File
@@ -0,0 +1,331 @@
use super::*;
use crate::app_icon::freedesktop;
#[test]
fn mips_filter_linear_premultiplied_pixels_including_odd_edges() {
let d = mip_chain(3, 1, &[255, 0, 0, 255, 0, 255, 0, 0, 255, 0, 0, 255]).unwrap();
assert_eq!(d.mips.len(), 2);
assert_eq!(&d.mips[0].pixels[4..8], &[0, 0, 0, 0]);
assert_eq!(d.mips[1].pixels[3], 170);
assert_eq!(d.mips[1].pixels[1], 0); // no transparent-green fringe
assert!((d.mips[1].pixels[0] as i32 - 213).abs() <= 1);
let gray = mip_chain(2, 1, &[0, 0, 0, 255, 255, 255, 255, 255]).unwrap();
assert_eq!(gray.mips[1].pixels, [188, 188, 188, 255]);
let tail = mip_chain(3, 1, &[255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap();
assert_eq!(tail.mips[1].pixels, [0, 0, 0, 0], "alpha rounded to zero cannot emit light");
}
#[test]
fn decoded_pixels_wake_windows_only_once_the_image_reports_ready() {
let image = Image::new(Arc::new(State { id: [0; 32], pixels: Pixels::new(), decoded: OnceLock::new() }));
let seen = Arc::new(Mutex::new(Vec::new()));
let (probe, record) = (image.clone(), seen.clone());
let wake = rune_core::live::Wake::new(Arc::new(move || {
record.lock().unwrap().push((probe.is_ready(), probe.size()));
}));
let _subscription = image.pixels().source.subscribe(&wake);
image.finish(mip_chain(2, 1, &[0, 0, 0, 255, 255, 255, 255, 255]));
assert_eq!(*seen.lock().unwrap(), [(true, Some([2, 1]))]);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_small_image_queued_behind_a_large_one_decodes_without_waiting_for_it() {
if std::thread::available_parallelism().map_or(1, |n| n.get()) < 2 { return; }
let (tx, rx) = mpsc::channel();
let caller = std::thread::current().id();
let cache = ImageCache::new(Arc::new(move || { tx.send(std::thread::current().id()).ok(); }));
let (release, gate) = mpsc::channel();
let input = Input::Rgba(128, 128, vec![128; 128 * 128 * 4].into());
let large = cache.request([8; 32], Input::Gated(Box::new(input), gate));
let inline = cache.rgba(64, 64, vec![255; 64 * 64 * 4]);
assert_eq!(inline.size(), Some([64, 64]));
assert_eq!(rx.try_recv(), Ok(caller));
assert_eq!(rx.try_recv(), Err(mpsc::TryRecvError::Empty));
// Just over the inline limit: a second worker must finish this one.
let small = cache.rgba(65, 64, vec![255; 65 * 64 * 4]);
assert_ne!(rx.recv_timeout(std::time::Duration::from_secs(120)).unwrap(), caller);
assert_eq!(small.size(), Some([65, 64]));
assert!(!large.is_ready());
release.send(()).unwrap();
rx.recv_timeout(std::time::Duration::from_secs(120)).unwrap();
assert_eq!(large.size(), Some([128, 128]));
}
#[test]
fn cache_deduplicates_and_wakes_after_async_completion() {
let (tx, rx) = mpsc::channel();
let cache = ImageCache::new(Arc::new(move || { tx.send(()).unwrap(); }));
let queued = || cache.rgba(65, 64, [20, 40, 60, 255].repeat(65 * 64));
let first = queued();
let second = queued();
assert!(Arc::ptr_eq(&first.0, &second.0));
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
assert_eq!(first.size(), Some([65, 64]));
assert_eq!(first.decoded().unwrap().unwrap().mips[0].pixels, [20, 40, 60, 255].repeat(65 * 64));
let invalid = cache.load(vec![0, 1, 2]);
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
assert!(invalid.error().is_some());
}
#[test]
fn a_fetch_is_wanted_while_a_handle_or_its_drawn_pixels_live() {
let image = Image::new(Arc::new(State { id: [0; 32], pixels: Pixels::new(), decoded: OnceLock::new() }));
let weak = Arc::downgrade(&image.0);
let drawn = image.pixels().clone();
drop(image);
assert!(wanted(&weak), "an element still draws it");
drop(drawn);
assert!(!wanted(&weak), "a guess replaced before its fetch runs fetches nothing");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn drawn_pixels_keep_their_image_cached_after_the_handle_drops() {
let (tx, rx) = mpsc::channel();
let cache = ImageCache::new(Arc::new(move || { tx.send(()).ok(); }));
let image = cache.rgba(1, 1, vec![20, 40, 60, 255]);
assert_eq!(image.size(), Some([1, 1]));
assert_eq!(rx.try_recv(), Ok(()), "a fresh inline decode wakes before returning");
assert_eq!(rx.try_recv(), Err(mpsc::TryRecvError::Empty));
// A view keeps only the pixels in its element, then asks again on the next build.
let drawn = image.pixels().clone();
let first = Arc::downgrade(&image.0);
drop(image);
let again = cache.rgba(1, 1, vec![20, 40, 60, 255]);
assert!(std::ptr::eq(first.as_ptr(), Arc::as_ptr(&again.0)), "the same entry, not a new request");
assert!(again.is_ready());
assert_eq!(rx.try_recv(), Err(mpsc::TryRecvError::Empty), "a cache hit does not wake");
drop((again, drawn));
assert!(first.upgrade().is_none(), "nothing left draws it, so it's released");
}
#[test]
fn png_jpeg_and_icns_decode_and_malformed_containers_fail() {
let source = image::RgbImage::from_pixel(8, 4, image::Rgb([20, 40, 60]));
for format in [image::ImageFormat::Png, image::ImageFormat::Jpeg] {
let mut encoded = std::io::Cursor::new(Vec::new());
source.write_to(&mut encoded, format).unwrap();
let bytes = encoded.into_inner();
assert_eq!(browser_decodes(&bytes), format == image::ImageFormat::Jpeg, "web decodes JPEG in the browser, PNG itself");
let d = decode(&bytes).unwrap();
assert_eq!((d.mips[0].width, d.mips[0].height), (8, 4));
assert_eq!((d.mips.last().unwrap().width, d.mips.last().unwrap().height), (1, 1));
if format == image::ImageFormat::Png {
let mut icns = b"icns".to_vec();
icns.extend_from_slice(&((bytes.len() + 16) as u32).to_be_bytes());
icns.extend_from_slice(b"icp4");
icns.extend_from_slice(&((bytes.len() + 8) as u32).to_be_bytes());
icns.extend_from_slice(&bytes);
assert!(!browser_decodes(&icns));
assert_eq!(decode(&icns).unwrap().mips[0].pixels, d.mips[0].pixels);
icns[12..16].copy_from_slice(&0u32.to_be_bytes());
assert!(decode(&icns).is_err());
}
}
assert!(mip_chain(0, 1, &[]).is_err());
assert!(mip_chain(1, 1, &[0]).is_err());
}
#[test]
fn a_jpeg_turns_upright_by_its_exif_orientation() {
// Red on the left, blue on the right, stored as the camera saw it.
let source = image::RgbImage::from_fn(16, 8, |x, _| if x < 8 { image::Rgb([255, 0, 0]) } else { image::Rgb([0, 0, 255]) });
let mut encoded = std::io::Cursor::new(Vec::new());
source.write_to(&mut encoded, image::ImageFormat::Jpeg).unwrap();
let jpeg = encoded.into_inner();
// An APP1 Exif segment after SOI: a little-endian TIFF header and one IFD entry,
// Orientation (0x0112) = 6, "rotate 90° clockwise to display".
let mut tiff = b"II*\0".to_vec();
tiff.extend_from_slice(&8u32.to_le_bytes());
tiff.extend_from_slice(&1u16.to_le_bytes());
tiff.extend_from_slice(&[0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0]);
tiff.extend_from_slice(&0u32.to_le_bytes());
let mut app1 = b"Exif\0\0".to_vec();
app1.extend_from_slice(&tiff);
let mut rotated = jpeg[..2].to_vec();
rotated.extend_from_slice(&[0xff, 0xe1]);
rotated.extend_from_slice(&(app1.len() as u16 + 2).to_be_bytes());
rotated.extend_from_slice(&app1);
rotated.extend_from_slice(&jpeg[2..]);
let plain = decode(&jpeg).unwrap();
assert_eq!((plain.mips[0].width, plain.mips[0].height), (16, 8));
let upright = decode(&rotated).unwrap();
let top = &upright.mips[0];
assert_eq!((top.width, top.height), (8, 16), "turned a quarter");
let at = |x: u32, y: u32| &top.pixels[((y * top.width + x) * 4) as usize..][..3];
assert!(at(4, 2)[0] > 200 && at(4, 2)[2] < 60, "the left (red) half is now on top: {:?}", at(4, 2));
assert!(at(4, 13)[2] > 200 && at(4, 13)[0] < 60, "the right (blue) half below: {:?}", at(4, 13));
}
#[test]
fn a_decoder_panic_fails_its_image_and_the_worker_goes_on() {
let (tx, rx) = mpsc::channel();
let cache = ImageCache::new(Arc::new(move || { tx.send(()).unwrap(); }));
let broken = cache.request([7; 32], Input::Panic);
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
assert_eq!(broken.error(), Some(&ImageError("image decoder panicked: decoder bug".into())));
let next = cache.rgba(65, 64, vec![255; 65 * 64 * 4]);
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
assert_eq!(next.size(), Some([65, 64]), "later queued images still load");
}
#[cfg(feature = "svg")]
#[test]
fn svg_rasterizes_at_the_requested_device_size_from_bytes_mime_files_and_svgz() {
const SVG: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="8" viewBox="0 0 16 8"><rect width="8" height="8" fill="#ff0000"/></svg>"##;
let crc = |data: &[u8]| !data.iter().fold(!0u32, |c, &b| (0..8).fold(c ^ b as u32, |c, _| (c >> 1) ^ (0xedb8_8320 & 0u32.wrapping_sub(c & 1))));
// Gzip with one stored deflate block.
let mut svgz = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff, 1];
svgz.extend_from_slice(&(SVG.len() as u16).to_le_bytes());
svgz.extend_from_slice(&(!(SVG.len() as u16)).to_le_bytes());
svgz.extend_from_slice(SVG);
svgz.extend_from_slice(&crc(SVG).to_le_bytes());
svgz.extend_from_slice(&(SVG.len() as u32).to_le_bytes());
let dir = std::env::temp_dir().join(format!("rune-svg-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("mark.svg"), SVG).unwrap();
std::fs::write(dir.join("mark.svgz"), &svgz).unwrap();
let cache = ImageCache::new(Arc::new(|| {}));
let cases = [
("load: twice its own size", cache.load(SVG), [32, 16]),
("load: sniffed svgz", cache.load(svgz.clone()), [32, 16]),
("svg: 24 pt at 2x", cache.svg(SVG, 24.0, 2.0), [48, 24]),
("svg: 16 pt at 3x", cache.svg(svgz.clone(), 16.0, 3.0), [48, 24]),
("mime", cache.load_mime(SVG, "image/svg+xml; charset=utf-8", 8.0, 2.0), [16, 8]),
("file .svg", cache.file(dir.join("mark.svg"), 32.0, 2.0), [64, 32]),
("file .svgz", cache.file(dir.join("mark.svgz"), 32.0, 1.0), [32, 16]),
];
for (what, image, size) in cases {
assert_eq!(image.wait(), Ok(size), "{what}");
let mip = &image.decoded().unwrap().unwrap().mips[0];
let at = |x: u32, y: u32| &mip.pixels[((y * mip.width + x) * 4) as usize..][..4];
assert_eq!(at(1, size[1] / 2), [255, 0, 0, 255], "{what}: the left half is red");
assert_eq!(at(size[0] - 2, size[1] / 2), [0, 0, 0, 0], "{what}: the right half is clear");
}
assert!(cache.load_mime(b"<svg".to_vec(), "image/svg+xml", 16.0, 2.0).wait().is_err(), "malformed SVG fails");
assert!(cache.file(dir.join("missing.svg"), 16.0, 2.0).wait().is_err());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn desktop_entries_resolve_the_closest_theme_size_then_scalable_then_pixmaps() {
let root = std::env::temp_dir().join(format!("rune-icon-theme-{}", std::process::id()));
let (user, system) = (root.join("user"), root.join("system"));
let put = |path: std::path::PathBuf| {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"icon").unwrap();
path
};
let entry = |icon: &str| {
let path = root.join(format!("{}.desktop", icon.replace('/', "_")));
std::fs::create_dir_all(&root).unwrap();
std::fs::write(&path, format!("[Desktop Entry]\nName=App\nIcon={icon}\n[Desktop Action new]\nIcon=other\n")).unwrap();
path
};
let dirs = [user.clone(), system.clone()];
put(system.join("icons/hicolor/32x32/apps/editor.png"));
let at_64 = put(user.join("icons/hicolor/64x64/apps/editor.png"));
let at_2x = put(system.join("icons/hicolor/48x48@2/apps/editor.png"));
put(system.join("icons/hicolor/256x256/apps/editor.png"));
let svg = put(system.join("icons/hicolor/scalable/apps/editor.svg"));
assert_eq!(freedesktop::icon_file(&entry("editor"), 48, &dirs), Some(at_64.clone()), "smallest size covering 48px");
assert_eq!(freedesktop::icon_file(&entry("editor"), 90, &dirs), Some(at_2x), "48x48@2 is 96px");
assert_eq!(freedesktop::icon_file(&entry("editor.png"), 48, &dirs), Some(at_64), "an extension in Icon= is ignored");
std::fs::remove_dir_all(system.join("icons/hicolor/256x256")).unwrap();
assert_eq!(freedesktop::icon_file(&entry("editor"), 512, &dirs), Some(svg), "scalable beats a too-small bitmap");
let pixmap = put(system.join("pixmaps/legacy.png"));
assert_eq!(freedesktop::icon_file(&entry("legacy"), 48, &dirs), Some(pixmap.clone()));
assert_eq!(freedesktop::icon_file(&entry(pixmap.to_str().unwrap()), 48, &dirs), Some(pixmap), "absolute Icon= path");
assert_eq!(freedesktop::icon_file(&entry("missing"), 48, &dirs), None);
assert_eq!(freedesktop::icon_name("[Desktop Action x]\nIcon=no\n"), None, "only the main group counts");
std::fs::remove_dir_all(&root).unwrap();
}
#[cfg(target_os = "windows")]
#[test]
fn app_icon_reads_an_executables_icon() {
let notepad = std::path::Path::new(r"C:\Windows\System32\notepad.exe");
if !notepad.is_file() { return; }
let (w, h, pixels) = app_icon_rgba(notepad, 48).unwrap();
assert_eq!((w, h), (48, 48));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] > 0));
}
#[cfg(target_os = "macos")]
#[test]
fn app_icon_rasterizes_calculator_off_the_main_thread_and_shares_handles() {
let cache = ImageCache::new(Arc::new(|| {}));
let icon = cache.app_icon("/System/Applications/Calculator.app", 32.0);
assert!(Arc::ptr_eq(&icon.0, &cache.app_icon("/System/Applications/Calculator.app", 32.0).0));
assert!(!Arc::ptr_eq(&icon.0, &cache.app_icon_scaled("/System/Applications/Calculator.app", 32.0, 1.0).0));
assert_eq!(icon.wait(), Ok([64, 64]));
let pixels = &icon.decoded().unwrap().unwrap().mips[0].pixels;
let opaque = pixels.chunks_exact(4).filter(|p| p[3] > 0).count();
assert!(opaque > 64 * 64 / 4, "icon is mostly empty: {opaque} visible pixels");
}
/// A small icon is the large one scaled down, not a different (on macOS 26 and later, a
/// framed "legacy") rendition.
#[cfg(target_os = "macos")]
#[test]
fn a_small_app_icon_matches_the_large_one_scaled_down() {
let dir = std::env::temp_dir().join(format!("rune-icon-bundle-{}", std::process::id()));
let app = synthetic_app(&dir);
let small = app_icon_rgba(&app, 32).unwrap().2;
let large = app_icon_rgba(&app, 256).unwrap().2;
std::fs::remove_dir_all(&dir).ok();
let (mut total, mut count) = (0u32, 0u32);
for y in 0..32 {
for x in 0..32 {
// Straight colour is noise where the icon is nearly transparent.
let solid = small[(y * 32 + x) * 4 + 3] >= 200;
for c in (if solid { 0 } else { 3 })..4 {
let block: u32 = (0..8).flat_map(|dy| (0..8).map(move |dx| (dx, dy)))
.map(|(dx, dy)| u32::from(large[((y * 8 + dy) * 256 + x * 8 + dx) * 4 + c])).sum();
total += (block / 64).abs_diff(u32::from(small[(y * 32 + x) * 4 + c]));
count += 1;
}
}
}
// The resampling filter rings on the tile's hard edge, so compare the mean, not the worst
// pixel. A different rendition (a framed or shrunken tile) differs across the whole icon.
let mean = total as f32 / count as f32;
assert!(mean < 12.0, "the 32 px icon differs from the 256 px one by {mean} on average");
}
/// A bundle whose only icon is a generated 256 px gradient, so the test does not depend on
/// the icons the installed macOS ships.
#[cfg(target_os = "macos")]
fn synthetic_app(dir: &std::path::Path) -> std::path::PathBuf {
let app = dir.join("Synthetic.app");
let resources = app.join("Contents/Resources");
std::fs::create_dir_all(&resources).unwrap();
std::fs::write(app.join("Contents/Info.plist"), concat!(
r#"<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>"#,
"<key>CFBundleIdentifier</key><string>dev.rune.synthetic-icon</string>",
"<key>CFBundleName</key><string>Synthetic</string>",
"<key>CFBundlePackageType</key><string>APPL</string>",
"<key>CFBundleIconFile</key><string>icon</string></dict></plist>",
)).unwrap();
let mut rgba = Vec::with_capacity(256 * 256 * 4);
for y in 0..256u32 {
for x in 0..256u32 {
let inside = (16..240).contains(&x) && (16..240).contains(&y);
rgba.extend_from_slice(&[x as u8, y as u8, (x + y) as u8 / 2, if inside { 255 } else { 0 }]);
}
}
let mut png = Vec::new();
let mut encoder = png::Encoder::new(&mut png, 256, 256);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&rgba).unwrap();
let mut icns = b"icns".to_vec();
icns.extend_from_slice(&((png.len() as u32 + 16).to_be_bytes()));
icns.extend_from_slice(b"ic08");
icns.extend_from_slice(&((png.len() as u32 + 8).to_be_bytes()));
icns.extend_from_slice(&png);
std::fs::write(resources.join("icon.icns"), icns).unwrap();
app
}