voelin-gpui: pictures keyed by the file and its stamp, Update.reloaded honoured

GPUI's img(path) keeps what it decoded under the path alone, so a
picture the engine writes again into the same cache file (an avatar or
a server icon that changed) stayed stale on screen. Pictures are now
drawn through a loader keyed by PictureKey, the path and the Stamp the
reference carries (voelin-ui-vm's ImageSource::File): a reference made
after the file changed is another picture, decoded anew, and the lists
that show it compare unequal and draw the row again. perform hands the
paths of Update.reloaded to pictures::forget_stale, which drops the
copies decoded under a stamp the file no longer has and the textures the
atlas made of them. The Avatar widget uses it.

Tests: the key follows the file; a picture rewritten into the same file
is decoded again and the old copy is dropped from the asset cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-27 23:40:36 +03:00
1 parent b133412700
commit d0bcf1f5b2
4 files changed
+229 -13

No files matched your search

+17 -1
View File
@@ -56,6 +56,7 @@ use voelin_ui_vm::social::logic::Social;
use crate::backend::Backend;
use crate::dev::Switches;
use crate::meter::Counters;
use crate::pictures;
use crate::signals::Signals;
use crate::theme::{Choice, VoelinTheme};
@@ -490,9 +491,24 @@ impl AppState {
/// ([`Signals::raise`]) once for as many updates as it has handled.
fn perform(&mut self, update: Update, cx: &mut Context<Self>) -> Refresh {
let Update {
refresh, status, commands, persist, warnings, rest, password, discover, ..
refresh,
status,
commands,
persist,
warnings,
rest,
password,
discover,
reloaded,
..
} = update;
self.log_warnings(warnings);
// The pictures the engine wrote again: what was decoded of the old
// ones goes ([`crate::pictures`]); the lists that show them compare
// the new reference unequal and draw the rows again.
for path in &reloaded {
pictures::forget_stale(path, cx);
}
for command in commands {
self.send(command);
}
+1
View File
@@ -12,6 +12,7 @@ pub mod dev;
pub mod engine;
pub mod fonts;
pub mod meter;
pub mod pictures;
pub mod shell;
pub mod signals;
pub mod swatch;
+199
View File
@@ -0,0 +1,199 @@
//! 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);
}
}
#[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)));
}
}
+12 -12
View File
@@ -6,12 +6,13 @@
use gpui_kit::{
App, ClickEvent, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, img, px,
svg,
RenderOnce, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, svg,
};
use gpui_kit::{ElementId, ObjectFit, StyledImage as _};
use voelin_ui_vm::Rgb;
use voelin_ui_vm::image::{ImageRef, ImageSource};
use voelin_ui_vm::image::ImageRef;
use crate::pictures::{PictureKey, picture};
use crate::theme::tokens::Rgba;
use crate::theme::{VoelinTheme, hsla};
@@ -70,8 +71,10 @@ pub fn tint(color: Rgb) -> Rgba {
/// An avatar: the picture when there is one (a file of the engine's cache),
/// else the initials on `tint`, square with rounded corners for a server
/// and round for a person, with a presence dot and a green ring while the
/// person's voice goes out. Pictures other than files of the cache are drawn
/// as initials until the slices that decode them (the chat's, the members').
/// person's voice goes out. The picture is keyed by the file and its stamp
/// ([`crate::pictures`]), so a picture the engine writes again shows. Pictures
/// other than files of the cache are drawn as initials until the slices that
/// decode them (the chat's).
#[derive(IntoElement)]
pub struct Avatar {
id: ElementId,
@@ -129,10 +132,7 @@ impl RenderOnce for Avatar {
let theme = VoelinTheme::global(cx);
let (c, m) = (&theme.colors, &theme.metrics);
let radius = if self.square { m.radius_lg } else { self.size / 2.0 };
let picture = match &*self.image {
ImageSource::File { path, .. } if self.image.size().width > 0 => Some(path.clone()),
_ => None,
};
let key = PictureKey::of(&self.image);
let face = div()
.size(px(self.size))
.flex_none()
@@ -141,9 +141,9 @@ impl RenderOnce for Avatar {
.flex()
.items_center()
.justify_center()
.bg(hsla(if picture.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match picture {
Some(path) => face.child(img(path).size_full().object_fit(ObjectFit::Cover)),
.bg(hsla(if key.is_some() { c.surface_3 } else { tint(self.tint) }));
let face = match key {
Some(key) => face.child(picture(key).size_full().object_fit(ObjectFit::Cover)),
None => face.child(
div()
.text_size(px(self.size * 0.38))