Files
VoelinClient/crates/voelin-gpui/src/pictures.rs
T
faumarayandClaude Sonnet 5.5 26302bcdde voelin-gpui: the members panel and the member card, the sample server's pictures and a talker
Slice 2, second half. The right panel of a server on screen (as wide as
ui.members_width) is everyone on the server in sections from voelin-ui-vm's
rows (server_members: those streaming first, then each server group), with
"Members - N", a search (search_members), and per person the avatar with its
presence dot and speaking ring, the name with the admin, priority, commander
and recording marks and their myTeamSpeak badges, what they do, the role,
LIVE, the mute marks and the hand of a person who needs talk power. It is a
cached pane over a virtual list that applies the model's row operations, and
the pane a talker redraws: nothing else of the window is told.

A click on a person opens their card over the panel (tree::member_card:
name, status, description, groups, badges, talk power, country) with a scrim
a click outside closes; it follows the person while open and goes when they
leave. Its buttons (volume, message, poke, friends, block) are the slices
of those dialogs.

Development: VOELIN_DEMO_UI now also delivers the first sample server's
avatars, icons, banners and badges as files of a folder of the state's own
(removed with it), and VOELIN_DEMO_TALK=10 makes a sample person start and
stop talking that many times a second through the app's events: what the
meter measures while someone talks.

Tests: the sections and the search, a talker redraws the members panel and
no other pane, the card (open, follows, closes three ways, goes with the
person), an avatar written again shows under a new key and the old copy goes
from the asset cache, the sample pictures and the talker.

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

206 lines
7.5 KiB
Rust

//! Pictures of the engine's cache on screen.
//!
//! The engine writes a picture that arrives again into the same file in its
//! cache (an avatar or a server icon that changed), and GPUI's `img(path)`
//! keeps what it decoded in the asset cache under the path alone, so the new
//! picture would never show. Here the key of a decoded picture is the file
//! and what the file was when the reference to it was made
//! ([`PictureKey`]: the path and the [`Stamp`] of `voelin_ui_vm::image`, its
//! length and time), so a reference made after the file changed is another
//! picture: it is decoded, and the lists that show it compare unequal and
//! draw the row again. What a changed file left in the cache (the decoded
//! copy under the old key, and the texture the atlas made of it) is dropped
//! when the engine says the file was written again
//! ([`forget_stale`], for `Update::reloaded`).
use std::collections::HashMap;
use std::future::Future;
use std::path::Path;
use std::sync::Arc;
use gpui_kit::{
App, Asset, Global, ImageAssetLoader, ImageCacheError, ImageSource, Img, RenderImage, Resource,
img,
};
use voelin_ui_vm::image::{ImageRef, ImageSource as Picture, Stamp};
/// What identifies a decoded picture: the file in the engine's cache and what
/// it was when the picture was referred to.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PictureKey {
path: Arc<Path>,
stamp: Stamp,
}
impl PictureKey {
/// The key of a reference to a file of the cache; none for no picture, a
/// picture that cannot be shown (missing or damaged: the reference's
/// size is none) and the pictures that are not files, which the slices
/// that decode them show.
pub fn of(image: &ImageRef) -> Option<Self> {
match &**image {
Picture::File { path, stamp } if image.size().width > 0 => {
Some(Self { path: Arc::from(path.as_path()), stamp: *stamp })
}
_ => None,
}
}
/// The file.
pub fn path(&self) -> &Path {
&self.path
}
}
/// Decodes the file of a [`PictureKey`] as `img(path)` does, keeping the
/// result under the whole key.
enum PictureLoader {}
impl Asset for PictureLoader {
type Source = PictureKey;
type Output = Result<Arc<RenderImage>, ImageCacheError>;
fn load(
source: PictureKey,
cx: &mut App,
) -> impl Future<Output = Self::Output> + Send + 'static {
<ImageAssetLoader as Asset>::load(Resource::Path(source.path), cx)
}
}
/// The keys that were drawn, by file: what [`forget_stale`] has to look at.
#[derive(Default)]
struct Drawn(HashMap<Arc<Path>, Vec<PictureKey>>);
impl Global for Drawn {}
/// Note that `key` is being drawn.
fn note(key: &PictureKey, cx: &mut App) {
let known = cx.has_global::<Drawn>()
&& cx.global::<Drawn>().0.get(key.path()).is_some_and(|keys| keys.contains(key));
if !known {
cx.default_global::<Drawn>().0.entry(key.path.clone()).or_default().push(key.clone());
}
}
/// The picture at `key` as an image element: decoded once per key, and again
/// when the file is another by the stamp. Give it a size and an object fit.
pub fn picture(key: PictureKey) -> Img {
img(ImageSource::Custom(Arc::new(move |window, cx| {
note(&key, cx);
window.use_asset::<PictureLoader>(&key, cx)
})))
}
/// The engine wrote the file at `path` again: drop what was decoded of it
/// under a stamp it no longer has, and the textures the atlas made of that.
/// The picture under the stamp it has now (a reference made after the write)
/// is kept; one that is made from the old file is drawn again when it is next
/// asked for.
pub fn forget_stale(path: &Path, cx: &mut App) {
if !cx.has_global::<Drawn>() {
return;
}
let now = Stamp::of(path);
let stale: Vec<PictureKey> = {
let Some(keys) = cx.global_mut::<Drawn>().0.get_mut(path) else { return };
let (stale, kept) = std::mem::take(keys).into_iter().partition(|key| key.stamp != now);
*keys = kept;
stale
};
for key in stale {
if let Some(Ok(image)) = cx.fetch_asset::<PictureLoader>(&key) {
cx.drop_image(image, None);
}
cx.remove_asset::<PictureLoader>(&key);
}
}
/// Whether the decoded copy of `key` is in the asset cache (the tests ask).
#[cfg(test)]
pub(crate) fn is_cached(key: &PictureKey, cx: &App) -> bool {
cx.has_asset::<PictureLoader>(key)
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use voelin_ui_vm::image::ImageSource as Source;
use super::*;
use crate::backend::testing::TempDir;
/// A PNG of `width` by 2 pixels.
fn png(width: u32) -> Vec<u8> {
voelin_ui_vm::dev::logic::demo_picture(width, 2, 1)
}
/// The key of a picture follows the file: a reference made after the
/// engine wrote the file again is another picture, one made before still
/// refers to the old, and what is not a file of the cache has none.
#[test]
fn the_key_of_a_picture_changes_when_the_file_does() {
let dir = TempDir::new("picture-key");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let first = Source::file(&path);
let key = PictureKey::of(&first).expect("a picture in the cache");
assert_eq!(key.path(), path);
assert_eq!(PictureKey::of(&Source::file(&path)), Some(key.clone()), "same file, same key");
std::fs::write(&path, png(7)).unwrap();
let second = PictureKey::of(&Source::file(&path)).unwrap();
assert_ne!(second, key, "the file was written again");
assert_eq!(PictureKey::of(&first), Some(key), "a reference made before keeps its own");
assert_eq!(PictureKey::of(&Source::none()), None);
assert_eq!(PictureKey::of(&Source::file(dir.0.join("missing"))), None);
std::fs::write(dir.0.join("damaged"), b"not a picture").unwrap();
assert_eq!(PictureKey::of(&Source::file(dir.0.join("damaged"))), None);
assert_eq!(PictureKey::of(&Source::rgba(1, 1, vec![0; 4])), None, "not a file");
}
/// A picture rewritten into the same file is decoded again under its new
/// key, and what was decoded of the old one is dropped when the engine says
/// the file was written again; the key of the file as it is stays.
#[gpui::test]
fn a_picture_written_again_is_decoded_again_and_the_old_copy_goes(cx: &mut TestAppContext) {
let dir = TempDir::new("picture-reload");
std::fs::create_dir_all(&dir.0).unwrap();
let path = dir.0.join("avatar");
std::fs::write(&path, png(3)).unwrap();
let old = PictureKey::of(&Source::file(&path)).unwrap();
let width = |cx: &mut TestAppContext, key: &PictureKey| {
cx.update(|cx| match cx.fetch_asset::<PictureLoader>(key) {
Some(Ok(image)) => Some(image.size(0).width.0),
_ => None,
})
};
cx.update(|cx| note(&old, cx));
assert_eq!(width(cx, &old), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &old), Some(3));
// The engine writes the file again, and the window draws the picture
// under the key of the file as it is now, before it is told so.
std::fs::write(&path, png(7)).unwrap();
let new = PictureKey::of(&Source::file(&path)).unwrap();
cx.update(|cx| note(&new, cx));
assert_eq!(width(cx, &new), None, "loading");
cx.run_until_parked();
assert_eq!(width(cx, &new), Some(7), "the new bytes, not the old ones");
assert_eq!(width(cx, &old), Some(3), "the old copy is still there");
cx.update(|cx| forget_stale(&path, cx));
assert!(!cx.update(|cx| cx.has_asset::<PictureLoader>(&old)), "the old copy is dropped");
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)), "the current key is kept");
assert_eq!(width(cx, &new), Some(7));
// Nothing more to forget; a file nobody drew is nothing to forget.
cx.update(|cx| forget_stale(&path, cx));
cx.update(|cx| forget_stale(&dir.0.join("never-drawn"), cx));
assert!(cx.update(|cx| cx.has_asset::<PictureLoader>(&new)));
}
}