Lighten the ring and the splash and follow the pointer and the scope (#84)
CI / core (pull_request) Successful in 1m36s

From the review of PR #94:
- The ring tessellates its fixed shapes once per set of ticks and size;
  a hover tessellates only the lit tick.
- The banner decodes its splash itself, one at a time, on GPUI's
  low-priority queue at below-normal thread priority: a splash asked
  for while another decodes waits, so two at most are ever held.
- Opening « Paramètres » gives back the splash and the grids' portraits.
- The grid has one hover transition: a card that leaves the grid puts
  its tick out, and a wheel that moves no card keeps it.
- The home column scrolls in a low window, so the grid stays reachable.
- Entering or leaving a champ select clears the banner until the new
  scope's statistics arrive.
- Tests: drawing the ring alone draws no grid and builds no card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-21 15:50:58 +01:00
1 parent d256dd61d2
commit 4fb8b37509
10 files changed
+495 -136

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ profile = ["gpui-kit/profiler"]
arena-tracker-core = { path = "../core" }
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
gpui-kit = "=0.9.1"
# Decodes the banner's splash at low priority (the same version as GPUI's and the core's).
image = { version = "0.25.10", default-features = false, features = ["jpeg"] }
[target.'cfg(windows)'.dependencies]
raw-window-handle = "0.6"
+100 -84
View File
@@ -1,44 +1,30 @@
//! The banner's illustration: the splash of one champion, decoded off the UI thread and held by
//! the banner alone, never by GPUI's app-wide asset cache (rule #1: memory in proportion to what
//! is shown).
//! The banner's illustration: the splash of one champion, decoded off the UI thread at low
//! priority and held by the banner alone, never by GPUI's app-wide asset cache (rule #1: memory in
//! proportion to what is shown, background work at low priority).
//!
//! It holds two splashes at most: the one shown and the one replacing it, which shows once
//! decoded. The one it replaces is then given back, in memory and in the window's atlas, as the
//! card portraits are (#77).
//! decoded. The one it replaces is then given back, in memory and in the windows' atlas, as the
//! card portraits are (#77). A decode cannot be stopped once started, so only one runs at a time:
//! a splash asked for meanwhile waits for its end.
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{Splash, SplashFocus};
use gpui_kit::*;
struct Held {
splash: Rc<Splash>,
item: ImageCacheItem,
}
impl Held {
fn new(splash: &Rc<Splash>, cx: &mut App) -> Held {
Held {
splash: splash.clone(),
item: ImageCacheItem::new(&Resource::Path(splash.path.clone().into()), cx),
}
}
/// Gives the image back, from `window`'s atlas and the others'; a load still running is
/// cancelled.
fn drop_image(self, window: Option<&mut Window>, cx: &mut App) {
if let Some(Ok(image)) = self.item.get() {
cx.drop_image(image, window);
}
}
}
use crate::worker::BelowNormal;
pub struct BannerArt {
shown: Option<Held>,
/// The splash to show next, while it decodes.
next: Option<Held>,
/// Loads started.
/// The splash shown, and its image; none when it could not be read.
shown: Option<(Rc<Splash>, Option<Arc<RenderImage>>)>,
/// The decode running, of which splash.
decoding: Option<(Rc<Splash>, Task<()>)>,
/// The splash the banner shows next: decoded when the running decode ends, if it is not
/// that one. None while the banner shows no illustration.
wanted: Option<Rc<Splash>>,
/// Decodes started.
#[cfg(test)]
pub(crate) loads: usize,
}
@@ -47,91 +33,121 @@ impl BannerArt {
pub fn new(cx: &mut App) -> Entity<BannerArt> {
let art = cx.new(|_| BannerArt {
shown: None,
next: None,
decoding: None,
wanted: None,
#[cfg(test)]
loads: 0,
});
// The page is gone: so are the splashes, from every window's atlas too.
cx.observe_release(&art, |art, cx| art.drop_all(None, cx))
// The page is gone: so is the splash, from every window's atlas too.
cx.observe_release(&art, |art, cx| art.drop_shown(None, cx))
.detach();
art
}
/// For the paint of `splash`: the image to paint and its focus. That is `splash` once
/// decoded, and until then the splash shown before it. The view painting is drawn again when
/// the decoding ends. A splash that cannot be read shows nothing.
/// decoded, and until then the splash shown before it. The art notifies when it changes. A
/// splash that cannot be read shows nothing.
pub fn image(
&mut self,
splash: &Rc<Splash>,
window: &mut Window,
cx: &mut App,
cx: &mut Context<Self>,
) -> Option<(Arc<RenderImage>, SplashFocus)> {
if self
if self.wanted.as_ref() != Some(splash) {
self.wanted = Some(splash.clone());
}
let shown_wanted = self
.shown
.as_ref()
.is_some_and(|held| held.splash == *splash)
.is_some_and(|(shown, _)| shown == splash);
if !shown_wanted && self.decoding.is_none() {
self.decode(splash.clone(), cx);
}
let (shown, image) = self.shown.as_ref()?;
Some((image.clone()?, shown.focus))
}
fn decode(&mut self, splash: Rc<Splash>, cx: &mut Context<Self>) {
#[cfg(test)]
{
if let Some(stale) = self.next.take() {
stale.drop_image(Some(window), cx);
}
} else {
if self
.next
self.loads += 1;
}
let path = splash.path.clone();
let task = cx.spawn(async move |art, cx| {
let image = cx
.background_executor()
.spawn_with_priority(Priority::Low, async move { decode(&path) })
.await;
let _ = art.update(cx, |art, cx| art.decoded(image, cx));
});
self.decoding = Some((splash, task));
}
/// The running decode ended: its splash replaces the one shown if the banner still wants
/// it, else it is dropped (it was never painted) and the wanted one decodes.
fn decoded(&mut self, image: Option<Arc<RenderImage>>, cx: &mut Context<Self>) {
let Some((splash, _)) = self.decoding.take() else {
return;
};
if self.wanted.as_ref() == Some(&splash) {
self.drop_shown(None, cx);
self.shown = Some((splash, image));
cx.notify();
} else if let Some(wanted) = self.wanted.clone()
&& self
.shown
.as_ref()
.is_some_and(|held| held.splash != *splash)
&& let Some(stale) = self.next.take()
{
stale.drop_image(Some(window), cx);
}
let next = self.next.get_or_insert_with(|| {
#[cfg(test)]
{
self.loads += 1;
}
Held::new(splash, cx)
});
if next.item.use_image(window).is_some() {
// Decoded, or failed: it replaces the one shown.
if let Some(replaced) = self.shown.take() {
replaced.drop_image(Some(window), cx);
}
self.shown = self.next.take();
}
.is_none_or(|(shown, _)| *shown != wanted)
{
self.decode(wanted, cx);
}
let shown = self.shown.as_ref()?;
let image = shown.item.use_image(window)?.ok()?;
Some((image, shown.splash.focus))
}
/// Drops both splashes, in memory and in the window's atlas, for a banner that is not shown
/// or has no illustration: a load still running is cancelled.
/// Gives back the splash shown, from `window`'s atlas and every other window's.
fn drop_shown(&mut self, window: Option<&mut Window>, cx: &mut App) {
if let Some((_, Some(image))) = self.shown.take() {
cx.drop_image(image, window);
}
}
/// Drops the splash, in memory and in the window's atlas, for a banner that is not shown or
/// has no illustration. A decode running ends unused.
pub fn release(&mut self, window: &mut Window, cx: &mut App) {
self.drop_all(Some(window), cx);
self.wanted = None;
self.drop_shown(Some(window), cx);
}
fn drop_all(&mut self, mut window: Option<&mut Window>, cx: &mut App) {
for held in [self.shown.take(), self.next.take()].into_iter().flatten() {
held.drop_image(window.as_deref_mut(), cx);
}
}
/// The splashes held, loaded or not.
/// The splashes held: shown, or decoding.
#[cfg(test)]
pub(crate) fn held(&self) -> Vec<std::path::PathBuf> {
[&self.shown, &self.next]
let shown = self.shown.as_ref().map(|(splash, _)| splash);
let decoding = self.decoding.as_ref().map(|(splash, _)| splash);
[shown, decoding]
.into_iter()
.flatten()
.map(|held| held.splash.path.clone())
.map(|splash| splash.path.clone())
.collect()
}
/// The splashes decoded.
/// The splash decoded and shown.
#[cfg(test)]
pub(crate) fn loaded(&self) -> Vec<Arc<RenderImage>> {
[&self.shown, &self.next]
.into_iter()
.flatten()
.filter_map(|held| held.item.get()?.ok())
self.shown
.iter()
.filter_map(|(_, image)| image.clone())
.collect()
}
}
/// Reads and decodes a stored splash (a JPEG) into what the GPU takes, BGRA, at below-normal
/// priority. None when it cannot be read.
fn decode(path: &Path) -> Option<Arc<RenderImage>> {
let _below = BelowNormal::enter();
let bytes = std::fs::read(path).ok()?;
let mut pixels = image::load_from_memory_with_format(&bytes, image::ImageFormat::Jpeg)
.ok()?
.into_rgba8();
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
Some(Arc::new(RenderImage::new(vec![image::Frame::new(pixels)])))
}
+47 -10
View File
@@ -104,6 +104,9 @@ pub struct CardGrid {
scroll: UniformListScrollHandle,
/// The card under the pointer, which shows its sheet.
hovered: Option<u32>,
/// How far the list was scrolled when last drawn: a wheel that leaves it there (at either
/// end) moves no card from under the pointer.
drawn_scroll: Pixels,
/// One per card id, kept across `set_cards` and dropped with the card.
focus: HashMap<u32, CardFocus>,
/// The cards changed since the focus handles were last matched to them.
@@ -131,6 +134,7 @@ impl CardGrid {
shown: Vec::new(),
scroll: UniformListScrollHandle::new(),
hovered: None,
drawn_scroll: Pixels::ZERO,
focus: HashMap::new(),
focus_stale: false,
fit_content: false,
@@ -163,6 +167,7 @@ impl CardGrid {
if *self.cards != *cards {
self.cards = cards;
self.focus_stale = true;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
@@ -193,10 +198,29 @@ impl CardGrid {
(false, Some(current)) if current == id => None,
(false, current) => current,
};
if next != self.hovered {
self.hovered = next;
cx.emit(CardHovered(next));
cx.notify();
self.hover(next, cx);
}
/// The one change of the card under the pointer: it draws the grid again and is told
/// (the ring lights that card's tick). True when it changed.
fn hover(&mut self, next: Option<u32>, cx: &mut Context<Self>) -> bool {
if next == self.hovered {
return false;
}
self.hovered = next;
cx.emit(CardHovered(next));
cx.notify();
true
}
/// The card under the pointer is no longer shown (filtered out, or gone with new cards):
/// none is hovered until the pointer moves again.
fn forget_hover_if_gone(&mut self, cx: &mut Context<Self>) {
let shown = |id| {
(self.shown.iter()).any(|&ix| self.cards.get(ix).is_some_and(|card| card.id == id))
};
if self.hovered.is_some_and(|id| !shown(id)) {
self.hover(None, cx);
}
}
@@ -231,13 +255,22 @@ impl CardGrid {
window.focus(&handle, cx);
}
/// How far down the list is scrolled, as its next layout will put it: a wheel past either end
/// is held there.
fn scrolled_to(&self) -> Pixels {
let handle = &self.scroll.0.borrow().base_handle;
handle
.offset()
.y
.max(-handle.max_offset().y)
.min(Pixels::ZERO)
}
/// The grid is not shown any more: its portraits are given back, in memory and in the
/// window's atlas, and load again when it is drawn.
pub fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// Nor is any of its cards under the pointer: the ring's tick goes out.
if self.hovered.take().is_some() {
cx.emit(CardHovered(None));
}
self.hover(None, cx);
let released = self
.images
.as_ref()
@@ -251,6 +284,7 @@ impl CardGrid {
pub fn set_shown(&mut self, shown: Vec<usize>, cx: &mut Context<Self>) {
if self.shown != shown {
self.shown = shown;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
@@ -344,9 +378,11 @@ impl CardGrid {
// 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| {
if grid.hovered.take().is_some() {
cx.emit(CardHovered(None));
cx.notify();
// The list has scrolled first. A grid that fits its content is moved by its
// parent's scrolling instead, which it cannot see.
let moved = grid.fit_content || grid.scrolled_to() != grid.drawn_scroll;
if moved {
grid.hover(None, cx);
}
}))
.on_action(cx.listener(|grid, _: &NextCard, window, cx| grid.move_focus(1, window, cx)))
@@ -365,6 +401,7 @@ impl Render for CardGrid {
if self.focus_stale {
self.sync_focus(window, cx);
}
self.drawn_scroll = self.scrolled_to();
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
+1
View File
@@ -153,6 +153,7 @@ impl RootView {
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.screen == Screen::Page {
self.screen = Screen::Settings;
self.page.update(cx, |page, cx| page.hidden(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
+204
View File
@@ -291,6 +291,8 @@ impl Page {
let subscriptions = vec![
Self::light_on_hover(&home_grid, cx),
Self::light_on_hover(&anvil_grid, cx),
// A splash decoded: the banner shows it.
cx.observe(&banner_art, |_, _, cx| cx.notify()),
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.search = ChampionSearch::new(&input.read(cx).value());
@@ -458,6 +460,17 @@ impl Page {
cx.notify();
}
/// The page gives way to another screen (« Paramètres »): what it shows is given back, the
/// grids' portraits and the banner's splash, in memory and in the window's atlas. They load
/// again when it is drawn.
pub fn hidden(&mut self, window: &mut Window, cx: &mut Context<Self>) {
for grid in [&self.home_grid, &self.anvil_grid, &self.others_grid] {
grid.update(cx, |grid, cx| grid.release_images(window, cx));
}
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
}
/// Starts a refresh, or queues one behind the refresh already running.
pub fn request_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
@@ -634,6 +647,9 @@ impl Page {
// A new champ select starts with « Autres champions » folded and searchless.
self.fold_others(window, cx);
self.reload_in_background(window, cx);
// Nor does the banner keep the previous scope's Challenge while the new one
// loads: its Season, its ticks and its splash go with the statistics.
self.prepare_banner(cx);
}
if changed_page {
cx.emit(ChampSelectTransition {
@@ -4586,4 +4602,192 @@ mod tests {
assert_eq!(art.size.width, banner.size.width);
assert_eq!(art.size.height, banner.size.height);
}
// Only the ring is invalidated: the grid is not drawn again, no card is built, and its fixed
// shapes are not tessellated again for a new lit tick.
#[gpui::test]
fn lighting_a_tick_draws_the_ring_alone_and_tessellates_only_that_tick(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let (ring, grid) = page.read_with(cx, |p, _| (p.ring.clone(), p.home_grid.clone()));
let grid_state = |cx: &mut VisualTestContext| {
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls)
})
};
let tessellations =
|cx: &mut VisualTestContext| ring.read_with(cx, |ring, _| ring.tessellations.get());
let before = grid_state(cx);
let shapes = tessellations(cx);
let renders = ring_renders(&page, cx);
for lit in [Some(5), Some(90), None] {
ring.update(cx, |ring, cx| ring.set_lit(lit, cx));
draw(cx);
}
assert_eq!(ring_renders(&page, cx), renders + 3);
assert_eq!(grid_state(cx), before);
assert_eq!(tessellations(cx), shapes);
// New ticks are tessellated once.
show(&page, cx, statistics(0, 171, champions(171)));
draw(cx);
assert_eq!(tessellations(cx), shapes + 1);
}
#[gpui::test]
fn a_splash_asked_for_while_another_decodes_waits_for_it(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-queue");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = rows_with_splashes(dir.path());
rows[2] = banner_champion(4, "Garen", 2, Some(on(11, 21)), 900);
rows[2].splash = Some(splash(dir.path(), "Garen"));
let last = |order: Vec<u32>| banner_statistics(rows.clone(), order, None);
show(&page, cx, last(vec![2, 1]));
draw_loaded(cx);
let ahri = loaded_splashes(&page, cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
// Brand starts decoding; Garen is asked for before it ends, and waits.
show(&page, cx, last(vec![1, 2]));
draw(cx);
show(&page, cx, last(vec![1, 2, 4]));
draw(cx);
assert_eq!(
held_splashes(&page, cx),
["Ahri.50.30.jpg", "Brand.50.30.jpg"]
);
cx.run_until_parked();
draw(cx);
assert_eq!(held_splashes(&page, cx), ["Garen.50.30.jpg"]);
assert!(!in_atlas(cx, &ahri[0]));
let loads = page.read_with(cx, |p, cx| p.banner_art.read(cx).loads);
assert_eq!(loads, 3);
}
#[gpui::test]
fn opening_another_screen_gives_back_the_splash_and_the_portraits(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-hidden");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = rows_with_splashes(dir.path());
for row in &mut rows {
let path = dir.path().join(format!("{}.card.jpg", row.champion.key));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
row.card_portrait = Some(path);
}
show(&page, cx, banner_statistics(rows, vec![2, 1], None));
draw_loaded(cx);
let images = page.read_with(cx, |p, cx| p.home_grid.read(cx).images().cloned().unwrap());
let portraits = images.read_with(cx, |images, _| images.loaded());
let splash = loaded_splashes(&page, cx);
assert!(!portraits.is_empty() && splash.len() == 1);
// Checked before any frame: here the page is the window's root and would be drawn
// again, where the app shows « Paramètres » in its place.
let (held, portraits_held, in_atlas) = cx.update(|window, cx| {
page.update(cx, |page, cx| page.hidden(window, cx));
let held = page.read(cx).banner_art.read(cx).held();
let portraits_held = images.read(cx).held();
let in_atlas = (portraits.iter().chain(&splash))
.filter(|image| window.has_image_atlas_entry(image))
.count();
(held, portraits_held, in_atlas)
});
assert!(held.is_empty(), "{held:?}");
assert!(portraits_held.is_empty(), "{portraits_held:?}");
assert_eq!(in_atlas, 0);
}
#[gpui::test]
fn in_a_low_window_the_home_scrolls_to_its_grid(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 30, champions(30)));
cx.simulate_resize(size(px(600.), px(340.)));
draw(cx);
let visible = |cx: &mut VisualTestContext| {
cx.debug_bounds("card-1")
.is_some_and(|b| b.top() < px(340.))
};
assert!(!visible(cx));
let banner = center(cx, "banner");
cx.simulate_event(ScrollEvent {
position: banner,
delta: ScrollDelta::Pixels(point(px(0.), px(-2000.))),
..Default::default()
});
draw(cx);
assert!(visible(cx));
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(1));
}
#[gpui::test]
fn the_tick_follows_the_card_actually_under_the_pointer(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(lit(cx), Some(1));
// A wheel at the top of the list moves no card: the tick stays, the ring is not drawn.
let renders = ring_renders(&page, cx);
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(400.))),
..Default::default()
});
draw(cx);
assert_eq!(lit(cx), Some(1));
assert_eq!(ring_renders(&page, cx), renders);
// The card leaves the grid (« Validés » here): its tick goes out.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(lit(cx), None);
}
#[gpui::test]
async fn the_banner_forgets_the_previous_scope_while_the_champ_select_loads(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("banner-scope");
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
cx.condition(&page, |p, _| p.stats.is_some()).await;
show(
&page,
&mut window,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
assert_eq!(
banner(&page, &mut window).title.text.as_ref(),
"2 / 5 champions validés"
);
send(&page, &mut window, &frames()[0]);
let text = banner(&page, &mut window);
assert!(text.title.text.is_empty(), "{:?}", text.title);
assert_eq!(text.splash, None);
assert!(ring_ticks(&page, &mut window).is_empty());
// Its own statistics arrive.
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert!(!banner(&page, &mut window).title.text.is_empty());
}
}
+4 -3
View File
@@ -151,7 +151,9 @@ impl Page {
}
}
}
vec![column.into_any_element()]
// In a low window the banner leaves the grid less than its least height: the column
// scrolls then, as the champ select's does.
vec![column.id("home").overflow_y_scroll().into_any_element()]
}
/// The sort selector: a sort icon and the choice, « Maîtrise » or « A–Z ». It stays on the
@@ -536,8 +538,7 @@ fn banner_art(
let image = canvas(
|_, _, _| {},
move |bounds, _, window, cx| {
let Some((image, focus)) = art.update(cx, |art, cx| art.image(&splash, window, cx))
else {
let Some((image, focus)) = art.update(cx, |art, cx| art.image(&splash, cx)) else {
return;
};
let frame = focus.banner_frame(bounds.size.width.as_f32(), bounds.size.height.as_f32());
+91 -37
View File
@@ -6,6 +6,7 @@
//! A cached view (rule #1): laid out from the style its parent gives, drawn again only when its
//! ticks or the lit one change, never by a hover or a scroll elsewhere.
use std::cell::RefCell;
use std::f32::consts::{FRAC_PI_2, TAU};
use std::rc::Rc;
@@ -128,13 +129,64 @@ impl Frame {
}
}
/// The ring's fixed shapes for one size and one set of ticks: tessellated once, painted again as
/// they are when only the lit tick changes.
struct Geometry {
bounds: Bounds<Pixels>,
/// One path per state of tick.
ticks: Vec<(ChampionState, Path<Pixels>)>,
crown: Option<Path<Pixels>>,
}
impl Geometry {
fn new(bounds: Bounds<Pixels>, ticks: &[Tick]) -> Geometry {
let frame = Frame::of(bounds);
let count = ticks.len();
let states = [
ChampionState::Completed,
ChampionState::InProgress,
ChampionState::NeverPlayed,
];
let ticks = states
.into_iter()
.filter_map(|state| {
let mut path = PathBuilder::fill();
let mut any = false;
for (index, tick) in ticks.iter().enumerate() {
if tick.state == state {
frame.add_tick(&mut path, index, count, state, shape(state).2);
any = true;
}
}
Some((state, path.build().ok().filter(|_| any)?))
})
.collect();
let mut crown = PathBuilder::fill();
let points: Vec<_> = CROWN
.iter()
.map(|&(x, y)| frame.point(CROWN_AT.0 + x * CROWN_SCALE, CROWN_AT.1 + y * CROWN_SCALE))
.collect();
crown.add_polygon(&points, true);
Geometry {
bounds,
ticks,
crown: crown.build().ok(),
}
}
}
pub struct Ring {
ticks: Rc<[Tick]>,
/// The champion whose card is under the pointer.
lit: Option<u32>,
/// Made by the paint, for its size; forgotten with the ticks.
geometry: Rc<RefCell<Option<Geometry>>>,
/// How many times it was drawn: the tests check it stays light.
#[cfg(test)]
pub(crate) renders: usize,
/// How many times its fixed shapes were tessellated.
#[cfg(test)]
pub(crate) tessellations: Rc<std::cell::Cell<usize>>,
}
impl Ring {
@@ -142,8 +194,11 @@ impl Ring {
Ring {
ticks: Rc::new([]),
lit: None,
geometry: Rc::default(),
#[cfg(test)]
renders: 0,
#[cfg(test)]
tessellations: Rc::default(),
}
}
@@ -151,6 +206,7 @@ impl Ring {
pub fn set_ticks(&mut self, ticks: Rc<[Tick]>, cx: &mut Context<Self>) {
if *self.ticks != *ticks {
self.ticks = ticks;
self.geometry.replace(None);
cx.notify();
}
}
@@ -181,14 +237,26 @@ impl Render for Ring {
self.renders += 1;
}
let theme = cx.theme();
let color = |state| match state {
ChampionState::Completed => theme.primary,
ChampionState::InProgress => ring_played(theme),
ChampionState::NeverPlayed => ring_never(theme),
};
let colors = [
(ChampionState::Completed, theme.primary),
(ChampionState::InProgress, ring_played(theme)),
(ChampionState::NeverPlayed, ring_never(theme)),
];
ChampionState::Completed,
ChampionState::InProgress,
ChampionState::NeverPlayed,
]
.map(|state| (state, color(state)));
let (disc, crown, lit_color) = (theme.background, theme.primary, theme.foreground);
let ticks = self.ticks.clone();
let lit = self.lit;
let geometry = self.geometry.clone();
#[cfg(test)]
let tessellations = self.tessellations.clone();
// The lit tick, and where it is.
let lit = (self.ticks.iter().enumerate())
.find(|(_, tick)| Some(tick.id) == self.lit)
.map(|(index, tick)| (index, tick.state));
div().size_full().debug_selector(|| "ring".into()).child(
canvas(
|_, _, _| {},
@@ -198,44 +266,30 @@ impl Render for Ring {
let centre = frame.point(C, C);
let disc_bounds = Bounds::centered_at(centre, size(radius * 2., radius * 2.));
window.paint_quad(fill(disc_bounds, disc).corner_radii(radius));
let count = ticks.len();
// One path per kind of tick, the lit one over them.
for (state, color) in colors {
let width = shape(state).2;
let mut path = PathBuilder::fill();
let mut any = false;
for (index, tick) in ticks.iter().enumerate() {
if tick.state == state {
frame.add_tick(&mut path, index, count, state, width);
any = true;
}
}
if any && let Ok(path) = path.build() {
window.paint_path(path, color);
}
let mut geometry = geometry.borrow_mut();
if geometry.as_ref().is_none_or(|g| g.bounds != bounds) {
#[cfg(test)]
tessellations.set(tessellations.get() + 1);
*geometry = Some(Geometry::new(bounds, &ticks));
}
if let Some((index, tick)) = ticks
.iter()
.enumerate()
.find(|(_, tick)| Some(tick.id) == lit)
{
let Some(geometry) = geometry.as_ref() else {
return;
};
for (state, path) in &geometry.ticks {
let color = colors.iter().find(|(s, _)| s == state).map(|(_, c)| *c);
window.paint_path(path.clone(), color.unwrap_or(crown));
}
if let Some(path) = &geometry.crown {
window.paint_path(path.clone(), crown);
}
// Only the lit tick is tessellated when the pointer changes card.
if let Some((index, state)) = lit {
let mut path = PathBuilder::fill();
frame.add_tick(&mut path, index, count, tick.state, 7.);
frame.add_tick(&mut path, index, ticks.len(), state, 7.);
if let Ok(path) = path.build() {
window.paint_path(path, lit_color);
}
}
let mut path = PathBuilder::fill();
let points: Vec<_> = CROWN
.iter()
.map(|&(x, y)| {
frame.point(CROWN_AT.0 + x * CROWN_SCALE, CROWN_AT.1 + y * CROWN_SCALE)
})
.collect();
path.add_polygon(&points, true);
if let Ok(path) = path.build() {
window.paint_path(path, crown);
}
},
)
.size_full(),
+44 -1
View File
@@ -134,7 +134,6 @@ const THREAD_PRIORITY_BELOW_NORMAL: i32 = -1;
unsafe extern "system" {
fn GetCurrentThread() -> *mut core::ffi::c_void;
fn SetThreadPriority(thread: *mut core::ffi::c_void, priority: i32) -> i32;
#[cfg(test)]
fn GetThreadPriority(thread: *mut core::ffi::c_void) -> i32;
}
@@ -149,6 +148,35 @@ fn lower_priority() {
}
}
/// Below-normal priority for the calling thread until dropped, which gives the previous one back:
/// for short work on a thread of GPUI's pool, which other tasks share (decoding a splash).
pub(crate) struct BelowNormal {
#[cfg(windows)]
previous: i32,
}
impl BelowNormal {
pub(crate) fn enter() -> BelowNormal {
#[cfg(windows)]
{
let previous = unsafe { GetThreadPriority(GetCurrentThread()) };
lower_priority();
BelowNormal { previous }
}
#[cfg(not(windows))]
BelowNormal {}
}
}
impl Drop for BelowNormal {
fn drop(&mut self) {
#[cfg(windows)]
unsafe {
SetThreadPriority(GetCurrentThread(), self.previous);
}
}
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded<T: Send + 'static>(
tx: Sender<T>,
@@ -514,4 +542,19 @@ mod tests {
});
assert_eq!(priority_rx.recv().unwrap(), THREAD_PRIORITY_BELOW_NORMAL);
}
#[test]
fn below_normal_lasts_until_dropped() {
std::thread::spawn(|| {
let priority = || unsafe { GetThreadPriority(GetCurrentThread()) };
let before = priority();
assert_ne!(before, THREAD_PRIORITY_BELOW_NORMAL);
let below = super::BelowNormal::enter();
assert_eq!(priority(), THREAD_PRIORITY_BELOW_NORMAL);
drop(below);
assert_eq!(priority(), before);
})
.join()
.unwrap();
}
}