From 815daf33cbeae35cfd68cea975cb4221c0d83079 Mon Sep 17 00:00:00 2001
From: TO
Date: Fri, 20 Nov 2026 21:41:06 +0100
Subject: [PATCH] Show the tall portraits on the cards, decoded only while
shown (#77)
The champions thread downloads the card portraits after the square ones
and tells the page at most once a second while they arrive, plus once at
the end, so each shows without a restart. A card shows its tall portrait,
the square icon while it is missing, else its plain background.
Each card grid reads its portraits through its own image cache: only the
cards it paints are loaded, and what its previous render did not paint is
dropped at its next render, from the GPU atlas too, and all of it with the
grid.
Co-Authored-By: Claude Opus 5.5
---
crates/app/src/card.rs | 27 +-
crates/app/src/card_grid.rs | 27 +-
crates/app/src/card_images.rs | 441 +++++++++++++++++++++++++
crates/app/src/main.rs | 1 +
crates/app/src/page.rs | 139 ++++++++
crates/app/src/worker.rs | 81 ++++-
crates/app/tests/fixtures/portrait.jpg | Bin 0 -> 473 bytes
docs/performance.md | 2 +-
8 files changed, 707 insertions(+), 11 deletions(-)
create mode 100644 crates/app/src/card_images.rs
create mode 100644 crates/app/tests/fixtures/portrait.jpg
diff --git a/crates/app/src/card.rs b/crates/app/src/card.rs
index 1f64cee..0a78226 100644
--- a/crates/app/src/card.rs
+++ b/crates/app/src/card.rs
@@ -74,7 +74,7 @@ impl Reason {
pub struct Card {
pub id: u32,
pub name: SharedString,
- /// The square icon today; the tall art later.
+ /// The tall portrait, else the square icon while the tall one is not downloaded yet.
pub portrait: Option,
pub marks: Marks,
/// In display order. A card with any reason is greyed.
@@ -106,7 +106,7 @@ impl Card {
Card {
id: row.champion.id,
name: row.champion.name.clone().into(),
- portrait: row.portrait.clone(),
+ portrait: row.card_portrait.clone().or_else(|| row.portrait.clone()),
marks,
reasons: if marks.completed {
vec![Reason::Completed]
@@ -354,6 +354,8 @@ fn mark(label: &'static str, on: bool) -> Div {
#[cfg(test)]
mod tests {
+ use std::path::PathBuf;
+
use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, Date, Unavailability};
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
@@ -530,6 +532,27 @@ mod tests {
assert!(!card.greyed());
}
+ #[test]
+ fn the_tall_portrait_is_shown_and_the_square_icon_stands_in_while_it_is_missing() {
+ let tall = PathBuf::from("portraits/cards/TwistedFate.jpg");
+ let square = PathBuf::from("portraits/TwistedFate.png");
+ let both = ChampionRow {
+ portrait: Some(square.clone()),
+ card_portrait: Some(tall.clone()),
+ ..row(None)
+ };
+ assert_eq!(Card::from_row(&both).portrait, Some(tall));
+
+ let downloading = ChampionRow {
+ card_portrait: None,
+ ..both
+ };
+ assert_eq!(Card::from_row(&downloading).portrait, Some(square));
+
+ // Neither: the card keeps its plain background.
+ assert_eq!(Card::from_row(&row(None)).portrait, None);
+ }
+
fn completed_row() -> ChampionRow {
row(Some(ChampionChallenge {
matches: 1,
diff --git a/crates/app/src/card_grid.rs b/crates/app/src/card_grid.rs
index 5d9619e..949d5b4 100644
--- a/crates/app/src/card_grid.rs
+++ b/crates/app/src/card_grid.rs
@@ -1,5 +1,6 @@
//! The card grid: all the cards a list shows, in rows of the same count, only the visible rows
-//! built. It is its own view because it owns the scrolling and the hover of its cards.
+//! built. It is its own view because it owns the scrolling and the hover of its cards, and the
+//! portraits they show (`card_images`).
use std::collections::HashMap;
use std::ops::Range;
@@ -10,6 +11,7 @@ use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
use crate::card::{ASPECT, Card, CardState, card};
+use crate::card_images::{self, CardImages};
use crate::page::PAGE_PADDING;
actions!(card_grid, [NextCard, PreviousCard]);
@@ -92,6 +94,8 @@ pub struct CardGrid {
/// All the rows built as a plain column, with no scrolling of its own: for a short list
/// whose height comes from its content (the Anvil champions row of a champ select).
fit_content: bool,
+ /// The portraits of the cards it paints, its own: made by its first render.
+ images: Option>,
/// Guard the light rendering in tests.
#[cfg(test)]
pub(crate) renders: usize,
@@ -111,6 +115,7 @@ impl CardGrid {
focus: HashMap::new(),
focus_stale: false,
fit_content: false,
+ images: None,
#[cfg(test)]
renders: 0,
#[cfg(test)]
@@ -232,6 +237,11 @@ impl CardGrid {
.collect()
}
+ #[cfg(test)]
+ pub(crate) fn images(&self) -> Option<&Entity> {
+ self.images.as_ref()
+ }
+
/// How far the grid is scrolled down.
#[cfg(test)]
pub(crate) fn scrolled(&self) -> Pixels {
@@ -285,9 +295,10 @@ impl CardGrid {
}
impl CardGrid {
- /// The grid's key context and what it reacts to besides its cards.
- fn wired(&self, root: Div, cx: &mut Context) -> Div {
- root.key_context(CONTEXT)
+ /// The grid's key context, its portraits and what it reacts to besides its cards.
+ fn wired(&self, root: Div, images: Entity, cx: &mut Context) -> Div {
+ card_images::provide(root, images)
+ .key_context(CONTEXT)
// A wheel scroll moves cards under a still pointer without a hover event: the
// sheet of the card that was under it would stay. The next mouse move hovers again.
.on_scroll(cx.listener(|grid, _: &ScrollEvent, _, cx| {
@@ -311,6 +322,10 @@ impl Render for CardGrid {
if self.focus_stale {
self.sync_focus(window, cx);
}
+ let images = (self.images)
+ .get_or_insert_with(|| CardImages::new(cx))
+ .clone();
+ images.update(cx, |images, cx| images.start_render(window, cx));
if self.shown.is_empty() {
let muted = cx.theme().muted_foreground;
return div()
@@ -329,11 +344,11 @@ impl Render for CardGrid {
.map(|ix| self.row(ix, metrics, window, cx))
.collect();
return self
- .wired(div().v_flex().w_full(), cx)
+ .wired(div().v_flex().w_full(), images, cx)
.children(rows)
.into_any_element();
}
- self.wired(div().relative().size_full(), cx)
+ self.wired(div().relative().size_full(), images, cx)
.child(
uniform_list(
"cards",
diff --git a/crates/app/src/card_images.rs b/crates/app/src/card_images.rs
new file mode 100644
index 0000000..d4e1c05
--- /dev/null
+++ b/crates/app/src/card_images.rs
@@ -0,0 +1,441 @@
+//! The portraits of a card grid: decoded only for the cards it paints, and freed, in memory and
+//! on the GPU, once it paints them no more (rule #1: memory in proportion to what is shown).
+//!
+//! Each grid owns one `CardImages`, which its cards' `img` elements read through (`provide`),
+//! never through GPUI's app-wide asset cache, which keeps every image it ever loaded. A grid may
+//! be a cached view: while it is not rendered again, its last paint is replayed with the images
+//! it used. So the cache only changes in the grid's own render: each one starts with
+//! `start_render`, which drops what the previous render did not paint, as no frame shows it.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use gpui_kit::*;
+
+struct Entry {
+ /// The image, or its load while it runs, or why it failed.
+ item: ImageCacheItem,
+ /// The last render that painted it.
+ painted: u64,
+}
+
+pub struct CardImages {
+ entries: HashMap,
+ /// The grid's render being drawn.
+ render: u64,
+ /// The grid is painting: `uniform_list` also lays rows out only to measure them, and a row
+ /// that is not painted is not shown, so its portraits are neither loaded nor kept.
+ painting: bool,
+ /// Loads started, to guard against retrying a failed one every frame.
+ #[cfg(test)]
+ pub(crate) loads: usize,
+}
+
+impl CardImages {
+ pub fn new(cx: &mut App) -> Entity {
+ let images = cx.new(|_| CardImages {
+ entries: HashMap::new(),
+ render: 0,
+ painting: false,
+ #[cfg(test)]
+ loads: 0,
+ });
+ // The grid is gone: so are its portraits, from every window's atlas too.
+ cx.observe_release(&images, |images, cx| {
+ for (_, entry) in images.entries.drain() {
+ if let Some(Ok(image)) = entry.item.get() {
+ cx.drop_image(image, None);
+ }
+ }
+ })
+ .detach();
+ images
+ }
+
+ /// Called first in each render of the grid. The frame on screen shows what the previous
+ /// render painted, and the frame being drawn shows only what this one will paint: anything
+ /// else is dropped, in memory and in the window's atlas. A load still running is cancelled.
+ pub fn start_render(&mut self, window: &mut Window, cx: &mut App) {
+ let previous = self.render;
+ self.entries.retain(|_, entry| {
+ if entry.painted == previous {
+ return true;
+ }
+ if let Some(Ok(image)) = entry.item.get() {
+ cx.drop_image(image, Some(window));
+ }
+ false
+ });
+ self.render += 1;
+ self.painting = false;
+ }
+}
+
+impl ImageCache for CardImages {
+ /// While the grid lays out, an image already there is given back and nothing is loaded.
+ /// While it paints, a missing image starts loading off the UI thread, and its end draws the
+ /// grid again. A failed load is kept, so it is not tried again while the card stays shown.
+ fn load(
+ &mut self,
+ resource: &Resource,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> Option, ImageCacheError>> {
+ if !self.painting {
+ return self
+ .entries
+ .get(resource)
+ .and_then(|entry| entry.item.get());
+ }
+ let render = self.render;
+ let entry = self.entries.entry(resource.clone()).or_insert_with(|| {
+ #[cfg(test)]
+ {
+ self.loads += 1;
+ }
+ Entry {
+ item: ImageCacheItem::new(resource, cx),
+ painted: render,
+ }
+ });
+ entry.painted = render;
+ entry.item.use_image(window)
+ }
+}
+
+/// `root`, whose `img` elements read through `images`. `root` gets its children after this:
+/// a mark painted before them tells `images` that the grid paints.
+pub fn provide(root: Div, images: Entity) -> Div {
+ let painting = images.clone();
+ root.image_cache(images).child(
+ canvas(
+ |_, _, _| {},
+ move |_, _, _, cx| painting.update(cx, |images, _| images.painting = true),
+ )
+ .absolute(),
+ )
+}
+
+#[cfg(test)]
+impl CardImages {
+ /// The portraits held, loaded or not, sorted.
+ pub(crate) fn held(&self) -> Vec {
+ let mut paths: Vec<_> = (self.entries.keys())
+ .filter_map(|resource| match resource {
+ Resource::Path(path) => Some(path.to_path_buf()),
+ _ => None,
+ })
+ .collect();
+ paths.sort();
+ paths
+ }
+
+ /// The images decoded.
+ pub(crate) fn loaded(&self) -> Vec> {
+ (self.entries.values())
+ .filter_map(|entry| entry.item.get()?.ok())
+ .collect()
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use std::path::{Path, PathBuf};
+ use std::rc::Rc;
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ use arena_tracker_core::Marks;
+ use gpui_kit::{
+ AppContext as _, Bounds, Context, Entity, ImageSource, InteractiveElement as _,
+ IntoElement, Modifiers, ParentElement as _, Render, RenderImage, ScrollDelta, ScrollEvent,
+ StyleRefinement, Styled as _, TestAppContext, VisualTestContext, Window, WindowBounds,
+ WindowOptions, div, point, px, red, size,
+ };
+
+ use super::CardImages;
+ use crate::card::Card;
+ use crate::card_grid::CardGrid;
+
+ /// A 68 x 100 JPEG, as the core stores the card portraits (smaller).
+ pub(crate) const PORTRAIT_JPEG: &[u8] = include_bytes!("../tests/fixtures/portrait.jpg");
+
+ /// A folder of its own in the system's temporary folder, removed with the value.
+ pub(crate) struct TestDir(PathBuf);
+
+ impl TestDir {
+ pub(crate) fn new(name: &str) -> TestDir {
+ static NEXT: AtomicUsize = AtomicUsize::new(0);
+ let path = std::env::temp_dir().join(format!(
+ "arena-tracker-{name}-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::SeqCst)
+ ));
+ let _ = std::fs::remove_dir_all(&path);
+ std::fs::create_dir_all(&path).unwrap();
+ TestDir(path)
+ }
+
+ pub(crate) fn path(&self) -> &Path {
+ &self.0
+ }
+ }
+
+ impl Drop for TestDir {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.0);
+ }
+ }
+
+ /// A bar with a button, as the page's header, above the grid as the home has it: cached.
+ struct Host {
+ grid: Option>,
+ }
+
+ impl Render for Host {
+ fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement {
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .child(
+ div().h(px(60.)).flex_shrink_0().child(
+ div()
+ .id("outside")
+ .debug_selector(|| "outside".into())
+ .w(px(200.))
+ .h_full()
+ .hover(|style| style.bg(red())),
+ ),
+ )
+ .children(self.grid.clone().map(|grid| {
+ grid.cached(StyleRefinement::default().w_full().flex_1().min_h(px(240.)))
+ }))
+ }
+ }
+
+ fn portrait(dir: &Path, id: u32) -> PathBuf {
+ dir.join(format!("{id}.jpg"))
+ }
+
+ /// A 1280 x 860 window, as the page tests', on `count` cards whose portraits are in `dir`,
+ /// written there when `write`.
+ fn open_grid(
+ cx: &mut TestAppContext,
+ dir: &Path,
+ count: u32,
+ write: bool,
+ ) -> (Entity, Entity, VisualTestContext) {
+ cx.update(gpui_kit::init);
+ let cards: Rc<[Card]> = (1..=count)
+ .map(|id| {
+ let path = portrait(dir, id);
+ if write {
+ std::fs::write(&path, PORTRAIT_JPEG).unwrap();
+ }
+ Card {
+ id,
+ name: format!("Champion {id:03}").into(),
+ portrait: Some(path),
+ marks: Marks {
+ played: false,
+ won: false,
+ completed: false,
+ },
+ reasons: Vec::new(),
+ sheet: Vec::new(),
+ }
+ })
+ .collect();
+ let (window, host) = cx.update(|cx| {
+ let options = WindowOptions {
+ window_bounds: Some(WindowBounds::Windowed(Bounds {
+ origin: point(px(0.), px(0.)),
+ size: size(px(1280.), px(860.)),
+ })),
+ ..Default::default()
+ };
+ gpui_kit::open_window(options, cx, |_, cx| {
+ let grid = cx.new(|cx| {
+ let mut grid = CardGrid::new();
+ grid.set_cards(cards, cx);
+ grid.set_shown((0..count as usize).collect(), cx);
+ grid
+ });
+ cx.new(|_| Host { grid: Some(grid) })
+ })
+ .unwrap()
+ });
+ let grid = cx.read(|cx| host.read(cx).grid.clone().unwrap());
+ (host, grid, VisualTestContext::from_window(window, cx))
+ }
+
+ fn draw(cx: &mut VisualTestContext) {
+ cx.update(|window, cx| window.draw(cx).clear(cx));
+ }
+
+ /// Draws, lets the started loads end, and draws what they drew again.
+ fn draw_loaded(cx: &mut VisualTestContext) {
+ draw(cx);
+ cx.run_until_parked();
+ draw(cx);
+ }
+
+ fn images(grid: &Entity, cx: &mut VisualTestContext) -> Entity {
+ grid.read_with(cx, |grid, _| grid.images().cloned())
+ .expect("the grid was not rendered")
+ }
+
+ /// The ids of the cards drawn in the last frame.
+ fn drawn(cx: &mut VisualTestContext, count: u32) -> Vec {
+ (1..=count)
+ .filter(|id| {
+ cx.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
+ .is_some()
+ })
+ .collect()
+ }
+
+ fn portraits(dir: &Path, ids: &[u32]) -> Vec {
+ let mut paths: Vec<_> = ids.iter().map(|&id| portrait(dir, id)).collect();
+ paths.sort();
+ paths
+ }
+
+ fn in_atlas(cx: &mut VisualTestContext, image: &RenderImage) -> bool {
+ cx.update(|window, _| window.has_image_atlas_entry(image))
+ }
+
+ fn scroll(cx: &mut VisualTestContext, by: f32) {
+ cx.simulate_event(ScrollEvent {
+ position: point(px(640.), px(400.)),
+ delta: ScrollDelta::Pixels(point(px(0.), px(by))),
+ ..Default::default()
+ });
+ }
+
+ #[gpui::test]
+ fn only_the_portraits_of_the_drawn_cards_are_kept(cx: &mut TestAppContext) {
+ let dir = TestDir::new("drawn-portraits");
+ let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
+ let cx = &mut window;
+ draw_loaded(cx);
+ let top = drawn(cx, 170);
+ // A few rows of 6, not the 170 cards; the first row is measured on every render, and
+ // its portraits are not kept for that.
+ assert!(top.contains(&1) && top.len() <= 6 * 4, "{top:?}");
+ let images = images(&grid, cx);
+ assert_eq!(
+ images.read_with(cx, |images, _| images.held()),
+ portraits(dir.path(), &top)
+ );
+ let first = images.read_with(cx, |images, _| images.loaded());
+ assert_eq!(first.len(), top.len(), "the portraits were not decoded");
+ assert!(first.iter().all(|image| in_atlas(cx, image)));
+ // Never through the app-wide asset cache, which would keep them.
+ cx.update(|_, cx| {
+ for &id in &top {
+ let source = ImageSource::from(portrait(dir.path(), id));
+ assert!(!source.is_asset_cached(cx), "card {id}");
+ }
+ });
+
+ // To the end: the last rows' portraits are loaded, and the first rows' ones are dropped,
+ // from the GPU atlas too.
+ scroll(cx, -100_000.);
+ draw_loaded(cx);
+ let bottom = drawn(cx, 170);
+ assert!(bottom.contains(&170) && !bottom.contains(&1), "{bottom:?}");
+ assert_eq!(
+ images.read_with(cx, |images, _| images.held()),
+ portraits(dir.path(), &bottom)
+ );
+ assert_eq!(
+ images.read_with(cx, |images, _| images.loaded()).len(),
+ bottom.len()
+ );
+ assert!(first.iter().all(|image| !in_atlas(cx, image)));
+
+ // Back to the top: loaded again.
+ let loads = images.read_with(cx, |images, _| images.loads);
+ scroll(cx, 100_000.);
+ draw_loaded(cx);
+ assert_eq!(drawn(cx, 170), top);
+ assert_eq!(
+ images.read_with(cx, |images, _| images.held()),
+ portraits(dir.path(), &top)
+ );
+ assert_eq!(
+ images.read_with(cx, |images, _| images.loads),
+ loads + top.len()
+ );
+ }
+
+ // The grid is a cached view: a frame that replays its last paint must keep its images.
+ #[gpui::test]
+ fn hovering_outside_the_grid_drops_no_portrait(cx: &mut TestAppContext) {
+ let dir = TestDir::new("hover-outside");
+ let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
+ let cx = &mut window;
+ draw_loaded(cx);
+ let images = images(&grid, cx);
+ let held = images.read_with(cx, |images, _| images.held());
+ let loaded = images.read_with(cx, |images, _| images.loaded());
+ let renders = grid.read_with(cx, |grid, _| grid.renders);
+ assert!(!loaded.is_empty());
+
+ let button = cx.debug_bounds("outside").unwrap().center();
+ for _ in 0..2 {
+ cx.simulate_mouse_move(button, None, Modifiers::none());
+ draw(cx);
+ cx.simulate_mouse_move(point(px(1000.), px(30.)), None, Modifiers::none());
+ draw(cx);
+ }
+ assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
+ assert_eq!(images.read_with(cx, |images, _| images.held()), held);
+ assert!(loaded.iter().all(|image| in_atlas(cx, image)));
+ }
+
+ #[gpui::test]
+ fn a_missing_portrait_leaves_the_card_readable_and_is_tried_once(cx: &mut TestAppContext) {
+ let dir = TestDir::new("missing-portraits");
+ let (_host, grid, mut window) = open_grid(cx, dir.path(), 30, false);
+ let cx = &mut window;
+ draw_loaded(cx);
+ let shown = drawn(cx, 30);
+ assert!(shown.contains(&1), "{shown:?}");
+ let images = images(&grid, cx);
+ assert!(images.read_with(cx, |images, _| images.loaded()).is_empty());
+ let loads = images.read_with(cx, |images, _| images.loads);
+ assert_eq!(loads, shown.len());
+
+ // Drawing the grid again, as a hover over its cards does, tries none of them again.
+ for _ in 0..3 {
+ grid.update(cx, |_, cx| cx.notify());
+ draw_loaded(cx);
+ }
+ assert_eq!(drawn(cx, 30), shown);
+ assert_eq!(images.read_with(cx, |images, _| images.loads), loads);
+ }
+
+ #[gpui::test]
+ fn the_portraits_are_freed_with_their_grid(cx: &mut TestAppContext) {
+ let dir = TestDir::new("freed-portraits");
+ let (host, grid, mut window) = open_grid(cx, dir.path(), 30, true);
+ let cx = &mut window;
+ draw_loaded(cx);
+ let loaded: Vec> =
+ images(&grid, cx).read_with(cx, |images, _| images.loaded());
+ assert!(!loaded.is_empty());
+ assert!(loaded.iter().all(|image| in_atlas(cx, image)));
+
+ host.update(cx, |host, cx| {
+ host.grid = None;
+ cx.notify();
+ });
+ drop(grid);
+ draw(cx);
+ cx.run_until_parked();
+ assert!(loaded.iter().all(|image| !in_atlas(cx, image)));
+ }
+}
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index 457f921..5ab19e3 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -2,6 +2,7 @@
mod card;
mod card_grid;
+mod card_images;
mod champion_table;
mod page;
#[cfg(feature = "profile")]
diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs
index a8a3aae..3709360 100644
--- a/crates/app/src/page.rs
+++ b/crates/app/src/page.rs
@@ -2987,4 +2987,143 @@ mod tests {
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
}
+
+ // The tall card portraits (#77).
+ use std::path::PathBuf;
+
+ use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
+
+ /// Joueur's tracker on the catalog, with the card portraits of `keys` on disk under `dir`.
+ fn tracker_with_portraits(dir: &Path, keys: &[&str]) -> Tracker {
+ let portraits = dir.join("portraits");
+ let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
+ .unwrap()
+ .with_seasons(vec![season("Saison", 2020)])
+ .with_champions(Box::new(Catalog), portraits.clone());
+ tracker.refresh_champions().unwrap();
+ tracker.sync(JOUEUR, &mut |_| {}).unwrap();
+ let cards = portraits.join("cards");
+ std::fs::create_dir_all(&cards).unwrap();
+ for key in keys {
+ std::fs::write(cards.join(format!("{key}.jpg")), PORTRAIT_JPEG).unwrap();
+ }
+ tracker
+ }
+
+ fn card_portrait(dir: &Path, key: &str) -> PathBuf {
+ dir.join("portraits")
+ .join("cards")
+ .join(format!("{key}.jpg"))
+ }
+
+ // The worker saves a portrait, then tells the page: the card shows it without a restart.
+ #[gpui::test]
+ async fn a_card_portrait_saved_while_the_app_runs_shows_once_the_worker_tells(
+ cx: &mut TestAppContext,
+ ) {
+ cx.executor().allow_parking();
+ let dir = TestDir::new("portrait-arrives");
+ let (page, mut window) =
+ open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &[]));
+ let grid = page.read_with(&window, |p, _| p.home_grid.clone());
+ let ahri = |grid: &CardGrid| {
+ let cards = grid.shown_cards().into_iter();
+ cards
+ .filter(|card| card.id == 103)
+ .map(|card| card.portrait)
+ .next()
+ };
+ assert_eq!(grid.read_with(&window, |grid, _| ahri(grid)), Some(None));
+ draw(&mut window);
+
+ let path = card_portrait(dir.path(), "Ahri");
+ std::fs::write(&path, PORTRAIT_JPEG).unwrap();
+ window
+ .update(|w, cx| page.update(cx, |p, cx| p.apply(crate::worker::Msg::Champions, w, cx)));
+ cx.condition(&grid, |grid, _| ahri(grid) == Some(Some(path.clone())))
+ .await;
+
+ // Drawn, through the grid's own cache.
+ draw(&mut window);
+ window.run_until_parked();
+ draw(&mut window);
+ let images = grid.read_with(&window, |grid, _| grid.images().cloned());
+ let images = images.expect("the grid was not drawn");
+ assert_eq!(images.read_with(&window, |i, _| i.held()), [path]);
+ assert_eq!(images.read_with(&window, |i, _| i.loaded()).len(), 1);
+ }
+
+ // The Anvil row is a grid of its own, not cached, with no `uniform_list`: its portraits go
+ // through its own cache too, never through the app-wide one.
+ #[gpui::test]
+ async fn the_anvil_row_reads_its_portraits_through_its_own_cache(cx: &mut TestAppContext) {
+ cx.executor().allow_parking();
+ let dir = TestDir::new("anvil-portraits");
+ let keys = ["Briar", "LeeSin", "Rumble", "Soraka", "XinZhao"];
+ let (page, mut window) =
+ open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
+ send(&page, &mut window, &frames()[0]);
+ cx.condition(&page, |p, _| p.stats.is_some()).await;
+ draw(&mut window);
+ window.run_until_parked();
+ draw(&mut window);
+
+ let grid = page.read_with(&window, |p, _| p.anvil_grid.clone());
+ let images = grid.read_with(&window, |grid, _| grid.images().cloned());
+ let images = images.expect("the row was not drawn");
+ let mut expected: Vec<_> = keys
+ .iter()
+ .map(|key| card_portrait(dir.path(), key))
+ .collect();
+ expected.sort();
+ assert_eq!(images.read_with(&window, |i, _| i.held()), expected);
+ let loaded = images.read_with(&window, |i, _| i.loaded());
+ assert_eq!(loaded.len(), keys.len());
+ window.update(|w, cx| {
+ assert!(loaded.iter().all(|image| w.has_image_atlas_entry(image)));
+ for path in &expected {
+ let source = gpui_kit::ImageSource::from(path.clone());
+ assert!(!source.is_asset_cached(cx), "{path:?}");
+ }
+ });
+ }
+
+ // Folding « Autres champions » drops its grid, and with it its portraits, on the GPU too.
+ #[gpui::test]
+ async fn folding_others_frees_its_portraits(cx: &mut TestAppContext) {
+ cx.executor().allow_parking();
+ let dir = TestDir::new("others-portraits");
+ let keys = ["Ahri", "Alistar", "Morgana", "Swain"];
+ let (page, mut window) =
+ open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
+ send(&page, &mut window, &frames()[0]);
+ cx.condition(&page, |p, _| p.stats.is_some()).await;
+ draw(&mut window);
+ click_others(&mut window);
+ window.run_until_parked();
+ draw(&mut window);
+ assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
+
+ let grid = page.read_with(&window, |p, _| p.others_grid.clone());
+ let images = grid.read_with(&window, |grid, _| grid.images().cloned());
+ let images = images.expect("the section was not drawn");
+ let loaded = images.read_with(&window, |i, _| i.loaded());
+ assert_eq!(loaded.len(), keys.len());
+ let in_atlas = |window: &mut VisualTestContext| {
+ window.update(|w, _| {
+ (loaded.iter())
+ .filter(|image| w.has_image_atlas_entry(image))
+ .count()
+ })
+ };
+ assert_eq!(in_atlas(&mut window), keys.len());
+ let weak = images.downgrade();
+ drop((images, grid));
+
+ click_others(&mut window);
+ assert!(!others_open(&page, &mut window));
+ window.run_until_parked();
+ assert!(weak.upgrade().is_none(), "the folded grid's cache is kept");
+ assert_eq!(in_atlas(&mut window), 0);
+ }
}
diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs
index 7280e8a..5e12848 100644
--- a/crates/app/src/worker.rs
+++ b/crates/app/src/worker.rs
@@ -5,7 +5,7 @@
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread;
-use std::time::{SystemTime, UNIX_EPOCH};
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
@@ -19,7 +19,7 @@ pub enum Msg {
ChampSelect(LiveChampSelect),
/// A sync is fetching Matches.
Progress(SyncProgress),
- /// The champion catalog and portraits were refreshed.
+ /// The champion catalog or portraits changed on disk: the statistics carry them.
Champions,
/// A follower round ended; `reload` when the stored data may have changed.
Round {
@@ -77,6 +77,48 @@ impl RefreshGate {
}
}
+/// While card portraits keep arriving, how often the page is told: each time, it reloads its
+/// statistics to show them.
+const PORTRAITS_TOLD_EVERY: Duration = Duration::from_secs(1);
+
+/// Spaces out what saved portraits cause: the first save is told at once, the next ones at most
+/// once per `every`, and one left untold when the pass ends is told then. No timer: a save or
+/// the end of the pass is what tells.
+struct Throttle {
+ every: Duration,
+ last_told: Option,
+ untold: bool,
+}
+
+impl Throttle {
+ fn new(every: Duration) -> Throttle {
+ Throttle {
+ every,
+ last_told: None,
+ untold: false,
+ }
+ }
+
+ /// A portrait was saved at `now`: true when it must be told now.
+ fn saved(&mut self, now: Instant) -> bool {
+ if self
+ .last_told
+ .is_some_and(|last| now.duration_since(last) < self.every)
+ {
+ self.untold = true;
+ return false;
+ }
+ self.last_told = Some(now);
+ self.untold = false;
+ true
+ }
+
+ /// The pass ended: true when a save is still untold.
+ fn finished(self) -> bool {
+ self.untold
+ }
+}
+
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -130,6 +172,17 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
+ // The tall card portraits after the square ones, which the Statistiques table uses. They
+ // show as they arrive, without a restart, the page reloading at most once a second.
+ let mut throttle = Throttle::new(PORTRAITS_TOLD_EVERY);
+ let _ = champions.refresh_card_portraits(&mut || {
+ if throttle.saved(Instant::now()) {
+ let _ = tx.try_send(Msg::Champions);
+ }
+ });
+ if throttle.finished() {
+ let _ = tx.try_send(Msg::Champions);
+ }
});
// Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks.
let (wake, rounds) = std::sync::mpsc::sync_channel(1);
@@ -377,6 +430,30 @@ mod tests {
));
}
+ #[test]
+ fn saved_portraits_are_told_at_most_once_a_second_and_the_last_ones_at_the_end() {
+ let start = Instant::now();
+ let at = |ms: u64| start + Duration::from_millis(ms);
+ let mut throttle = Throttle::new(Duration::from_secs(1));
+ assert!(throttle.saved(at(0)), "the first save waits");
+ assert!(!throttle.saved(at(300)));
+ assert!(!throttle.saved(at(999)));
+ assert!(throttle.saved(at(1000)));
+ assert!(!throttle.saved(at(1500)));
+ // The save at 1.5 s is told when the pass ends.
+ assert!(throttle.finished());
+
+ // The last save was told: nothing more at the end.
+ let mut throttle = Throttle::new(Duration::from_secs(1));
+ assert!(throttle.saved(at(0)));
+ assert!(!throttle.saved(at(10)));
+ assert!(throttle.saved(at(2000)));
+ assert!(!throttle.finished());
+
+ // Nothing saved, nothing told.
+ assert!(!Throttle::new(Duration::from_secs(1)).finished());
+ }
+
#[test]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default();
diff --git a/crates/app/tests/fixtures/portrait.jpg b/crates/app/tests/fixtures/portrait.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..08545d33b96afd8962927e4071747dd1df4e733d
GIT binary patch
literal 473
zcmex=^lOiET&UP@Y7ModgWM?qOlT~kX_QeM|USHnP6LsJ7}2qQZ?I~NC+Fc+7w
zhLo6;2Fc+60R}-1h7<-DW=16jCP7AKLB{__7{q~21vwT8urRZMBm^)dgc1co5+HF@
z9n6d%9ioD0!VC;T|8FtyFf#(JV-{qvXLzc!lUH=sIoQX^p_7
zYA)fMIT}kcd*5sm33RU3Z50W)cRJBk#C&5bE9YykD_??4j*2eLs?u2Kni(~(OCvBU
zZ26)tk+9Ae8i}dPH(gw&vFY;7R4$` (from WSL, pass it through `WSLENV`, e.g. `WSLENV=ARENA_TRACKER_PROFILE/p:ARENA_TRACKER_HIDE`). Every second it appends the frames GPUI drew (`draw`: total, `request_layout`, `prepaint`, `paint` in ms), their presentation (`present`) and the views' own time (`view`, recorded by GPUI from 0.5 ms). `ARENA_TRACKER_HIDE=`, read at start, removes parts of the page so that a part's cost is the difference with the full page under the hover probe: `header`, `banners` (both tabs), then for « Statistiques » `tiles`, `placements`, `completed`, `attempts` (the three charts keep their height), `tabs`, `table`, and for « Défi » `home-header` (Season, title and counter), `home-tools` (the heading row: title, count, filters and search), `cards` (the card grid), and during an Arena champ select `anvil` (the Anvil champions heading and row, which take the place of `home-tools` and `cards`), then `others` (the « Autres champions » section: its header and, when open, its search and grid).
- **Memory**: working set of `arena-tracker.exe` in Task Manager, or `Get-Process arena-tracker` in PowerShell, once the page is fully loaded.
-- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is a cached view (#31), and « Défi » never renders it (a structural test guards that too). The home's card grid is the other (#72): its size comes from its style, and structural tests check that hovering outside it does not render its cards and that hovering or scrolling it recomputes no statistics. A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache.
+- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is a cached view (#31), and « Défi » never renders it (a structural test guards that too). The home's card grid is the other (#72): its size comes from its style, and structural tests check that hovering outside it does not render its cards and that hovering or scrolling it recomputes no statistics. Each card grid reads its portraits through its own image cache, never GPUI's app-wide one, and keeps only those of the cards it paints (#77): structural tests check that scrolling drops the others, from the GPU atlas too, and that hovering outside the grid drops none. A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache.
GPUI and gpui-component are not modified to meet a budget: the app's own rendering cost is the lever (ADR-0004).