From ee2ab5cc33aa7812b27a75a825c61b483df715ae Mon Sep 17 00:00:00 2001 From: TO Date: Sun, 22 Nov 2026 16:06:03 +0100 Subject: [PATCH] Prepare the held grid on arrival and keep the followed game apart from older Matches (#89) Co-Authored-By: Claude Opus 5.5 --- crates/app/src/banner_art.rs | 6 + crates/app/src/card_grid.rs | 5 + crates/app/src/motion.rs | 29 +-- crates/app/src/page.rs | 414 +++++++++++++++++++++++++++++------ crates/app/src/page/home.rs | 6 +- crates/app/src/ring.rs | 199 +++++++++-------- crates/core/src/follow.rs | 45 +++- crates/core/tests/follow.rs | 48 +++- docs/performance.md | 2 +- 9 files changed, 572 insertions(+), 182 deletions(-) diff --git a/crates/app/src/banner_art.rs b/crates/app/src/banner_art.rs index 12c9a0a..859fbab 100644 --- a/crates/app/src/banner_art.rs +++ b/crates/app/src/banner_art.rs @@ -79,6 +79,12 @@ impl BannerArt { art } + /// A splash is settling in. + #[cfg(test)] + pub(crate) fn revealing(&self) -> bool { + self.reveal.is_some() + } + /// Shows `target` as the splash of a champion just Completed: it settles in. pub(crate) fn reveal(&mut self, target: Option>, cx: &mut Context) { self.set_target(target, cx); diff --git a/crates/app/src/card_grid.rs b/crates/app/src/card_grid.rs index 71262af..9273fe9 100644 --- a/crates/app/src/card_grid.rs +++ b/crates/app/src/card_grid.rs @@ -340,6 +340,11 @@ impl CardGrid { } } + /// The indices of the cards shown, in order. + pub fn shown(&self) -> &[usize] { + &self.shown + } + pub fn set_shown(&mut self, shown: Vec, cx: &mut Context) { if self.shown != shown { self.shown = shown; diff --git a/crates/app/src/motion.rs b/crates/app/src/motion.rs index 0a0f701..3e82f47 100644 --- a/crates/app/src/motion.rs +++ b/crates/app/src/motion.rs @@ -38,6 +38,7 @@ pub(crate) const COUNTER_ROLL: f32 = 0.7; pub(crate) struct MatchAnimation { pub start: Instant, pub end: MatchEnd, + pub champion_id: u32, /// The champion's tick, among `count`. pub index: usize, pub count: usize, @@ -79,10 +80,17 @@ pub(crate) struct Deferred { waiting: Option, } -impl Deferred { - pub fn new() -> Self { +impl Default for Deferred { + fn default() -> Self { Deferred { waiting: None } } +} + +impl Deferred { + /// The animation waiting, if any. + pub fn waiting(&self) -> Option<&A> { + self.waiting.as_ref() + } /// Gives back the animation to play now when « Défi » is visible, else keeps it if it is the /// strongest waiting. @@ -104,11 +112,6 @@ impl Deferred { pub fn shown(&mut self) -> Option { self.waiting.take() } - - /// A champ select starts: what waited is no longer news. - pub fn abandon(&mut self) { - self.waiting = None; - } } /// The screen leaving « Défi » or « Statistiques » goes under a veil of the page's background, @@ -264,13 +267,13 @@ mod tests { #[test] fn an_animation_asked_for_while_visible_plays_at_once() { - let mut deferred = Deferred::new(); + let mut deferred = Deferred::default(); assert_eq!(deferred.request(1, true), Some(1)); } #[test] fn of_the_animations_asked_for_while_hidden_only_the_strongest_plays_once_shown() { - let mut deferred = Deferred::new(); + let mut deferred = Deferred::default(); assert_eq!(deferred.request(1, false), None); assert_eq!(deferred.request(3, false), None); assert_eq!(deferred.request(2, false), None); @@ -279,14 +282,6 @@ mod tests { assert_eq!(deferred.shown(), None); } - #[test] - fn a_champ_select_that_starts_abandons_the_animations_waiting() { - let mut deferred = Deferred::new(); - deferred.request(2, false); - deferred.abandon(); - assert_eq!(deferred.shown(), None); - } - fn at(start: Instant, ms: u64) -> Instant { start + Duration::from_millis(ms) } diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index d4f3e82..e092330 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -130,12 +130,22 @@ enum Tab { Statistics, } +/// A followed Match waiting to play: of several, the strongest plays, and the most recent of the +/// strongest. The order of the fields is that ranking (derived `Ord`). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +struct WaitingMatch { + end: MatchEnd, + started_at_ms: i64, + champion_id: u32, +} + /// The end of a followed Match on « Défi », from the round that stored it to the end of its /// animation; `Page::end_match` drops it all. #[derive(Default)] struct MatchPlayback { - /// The Match to play once the statistics with it are shown and « Défi » is in front. - queued: Option, + /// The Match to play once the statistics with it are shown and « Défi » is in front: it + /// waits there whatever hides « Défi » meanwhile. + waiting: Deferred, /// The statistics shown do not hold the queued Match yet. stats_pending: bool, /// The animation running, fixed when it started. @@ -144,14 +154,26 @@ struct MatchPlayback { previous_banner: Option, /// The champion's card before the Match, drawn until its change lands. previous_card: Option>, + /// The champion whose card the grid showed: it stays shown until the animation ends, even + /// if the filter now leaves it out, so that it changes in place. + kept_card: Option, } impl MatchPlayback { fn active(&self) -> bool { - self.queued.is_some() || self.animation.is_some() + self.waiting.waiting().is_some() || self.animation.is_some() } } +/// The home grid of new statistics that arrived while the pointer held it still, prepared on +/// their arrival: the pointer leaving only puts it in place (rule #1). +struct NextHome { + order: Vec, + cards: Rc<[Card]>, + shown: Vec, + count: SharedString, +} + pub struct Page { tracker: Arc, tx: Sender, @@ -194,14 +216,14 @@ pub struct Page { lifted_by_keyboard: Option>, /// « Paramètres » stands in for the page. covered: bool, - /// The animation asked for while « Défi » was not visible. - deferred: Deferred, /// The end of a followed Match, from its round to the end of its animation. playback: MatchPlayback, /// The pointer was on the home grid when a followed Match changed it: its cards change in /// place, and the order, the filter and the count wait for the pointer to leave so that /// nothing moves under it. hold_grid: bool, + /// While `hold_grid`, the grid it waits to show, once the statistics are there. + next_home: Option, /// The animations played, in order. #[cfg(test)] played: Vec, @@ -373,7 +395,7 @@ impl Page { cx.subscribe(&home_search_input, |this, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { this.home_search = ChampionSearch::new(&input.read(cx).value()); - this.refresh_home(cx); + this.home_filtered(cx); } }), cx.subscribe( @@ -482,9 +504,9 @@ impl Page { lifts: Lifts::new(), lifted_by_keyboard: None, covered: false, - deferred: Deferred::new(), playback: MatchPlayback::default(), hold_grid: false, + next_home: None, #[cfg(test)] played: Vec::new(), season, @@ -564,15 +586,18 @@ impl Page { self.play_waiting(window, cx); } - /// Ends the end of a followed Match, waiting or playing: the banner shows its splash again. + /// Ends the end of a followed Match, waiting or playing: the banner shows its splash again, + /// and the champion's card leaves the grid if the filter or the search leave it out. fn end_match(&mut self, cx: &mut Context) { - if self.playback.active() { + // A Match the ring had no tick for left only its kept card. + let active = self.playback.active() || self.playback.kept_card.is_some(); + self.playback = MatchPlayback::default(); + if active { self.banner_art.update(cx, |art, cx| { art.set_target(self.banner.splash.clone(), cx); }); + self.refresh_home(cx); } - self.deferred.abandon(); - self.playback = MatchPlayback::default(); } /// The end of a followed Match: it plays once the statistics with it are shown and « Défi » @@ -586,7 +611,7 @@ impl Page { if self.playback.animation.is_some() { self.end_match(cx); } - if self.playback.queued.is_none() { + if self.playback.waiting.waiting().is_none() { self.playback.previous_banner = Some(if self.in_champ_select() { home::BannerContent::new(self.home_season.as_ref(), self.home_statistics()) } else { @@ -594,16 +619,20 @@ impl Page { }); } self.playback.stats_pending = true; - self.deferred.request(event.end, false); - let rank = |m: &FollowedMatch| (m.end, m.started_at_ms); - if (self.playback.queued.as_ref()).is_some_and(|queued| rank(queued) > rank(&event)) { - return; + let waiting = WaitingMatch { + end: event.end, + started_at_ms: event.started_at_ms, + champion_id: event.champion_id, + }; + self.playback.waiting.request(waiting, false); + if self.playback.waiting.waiting() == Some(&waiting) { + let grid = self.home_grid.read(cx); + let card = (grid.cards().iter()).position(|c| c.id == event.champion_id); + self.playback.previous_card = card.map(|ix| Rc::new(grid.cards()[ix].clone())); + self.playback.kept_card = card + .filter(|ix| grid.shown().contains(ix)) + .map(|_| event.champion_id); } - self.playback.previous_card = (self.home_grid.read(cx).cards().iter()) - .find(|c| c.id == event.champion_id) - .cloned() - .map(Rc::new); - self.playback.queued = Some(event); } /// Whether « Défi » is in front of the player. A window merely covered by another cannot @@ -623,17 +652,15 @@ impl Page { if self.challenge_visible(window) && !cx.reduce_motion() && !self.playback.stats_pending - && let Some(end) = self.deferred.shown() + && let Some(waiting) = self.playback.waiting.shown() { #[cfg(test)] - self.played.push(end); - if let Some(event) = self.playback.queued.take() { - self.playback.animation = self.ring.read(cx).animation( - event.champion_id, - end, - cx.background_executor().now(), - ); - } + self.played.push(waiting.end); + self.playback.animation = self.ring.read(cx).animation( + waiting.champion_id, + waiting.end, + cx.background_executor().now(), + ); // Under the comet, the splash of the champion validé before. let target = (self.playback.previous_banner.as_ref()) .filter(|_| { @@ -646,6 +673,10 @@ impl Page { .clone(); self.banner_art .update(cx, |art, cx| art.set_target(target, cx)); + if self.playback.animation.is_none() { + // The ring has no tick for it: nothing plays. + self.end_match(cx); + } cx.notify(); } } @@ -789,6 +820,8 @@ impl Page { return; } self.shown_tab = self.tab; + // The home grid is no longer under the pointer. + self.release_home(cx); // The screen arriving was not kept up to date while hidden, and is prepared only now: a // switch undone under the veil prepares nothing. self.refresh_table(cx); @@ -867,7 +900,7 @@ impl Page { // The champ select is about the Challenge, whatever tab was open. self.tab = Tab::Challenge; // Nothing plays during a champ select: what waited is no longer news. - self.hold_grid = false; + self.stop_holding(); self.end_match(cx); self.end_fade(window, cx); // The home grid gives way to the champ select's sections. @@ -878,7 +911,7 @@ impl Page { self.anvil_grid .update(cx, |grid, cx| grid.release_images(window, cx)); // An animation asked for during the champ select plays on the home. - self.playback.stats_pending = self.playback.queued.is_some(); + self.playback.stats_pending = self.playback.active(); } } if switch { @@ -1069,8 +1102,8 @@ impl Page { self.settle_home_scope(); let viewed = self.viewed().map(|a| a.puuid.clone()); if previous_season != self.home_season || viewed != self.shown { + self.stop_holding(); self.end_match(cx); - self.hold_grid = false; } if computing || viewed != self.shown { self.stats_generation += 1; @@ -1231,13 +1264,16 @@ impl Page { .home_statistics() .map_or(&[][..], |s| s.rows.as_slice()); let cards = self.home_grid.read(cx).cards(); - self.hold_grid = rows.len() == cards.len() + let same = rows.len() == cards.len() && self.order.len() == rows.len() && self .order .iter() .zip(cards.iter()) .all(|(&ix, c)| rows.get(ix).is_some_and(|r| r.champion.id == c.id)); + if !same || self.in_champ_select() { + self.stop_holding(); + } } if !self.hold_grid { self.reorder(); @@ -1267,9 +1303,26 @@ impl Page { .update(cx, |select, cx| select.set_items(names, window, cx)); } self.refresh_table(cx); - // Held, the cards changed in place; which are shown, and their count, wait for the - // pointer to leave (`hold_grid`). - if !self.hold_grid { + if self.hold_grid { + // The cards changed in place; their order, which are shown and their count wait for + // the pointer to leave, prepared now. + let order = self.sorted_order(); + let rows = self + .home_statistics() + .map_or(&[][..], |s| s.rows.as_slice()); + let cards = order + .iter() + .filter_map(|&ix| rows.get(ix)) + .map(Card::from_row) + .collect(); + let shown = self.home_shown(&order); + self.next_home = Some(NextHome { + count: shown.len().to_string().into(), + order, + cards, + shown, + }); + } else { self.refresh_home(cx); } self.playback.stats_pending = false; @@ -1398,11 +1451,8 @@ impl Page { None if self.lit_by == Some(grid) => self.lit_by = None, None => return, } - if self.hold_grid && id.is_none() && grid == self.home_grid.entity_id() { - self.hold_grid = false; - self.reorder(); - self.prepare_home_cards(cx); - self.refresh_home(cx); + if id.is_none() && grid == self.home_grid.entity_id() { + self.release_home(cx); } self.ring.update(cx, |ring, cx| ring.set_lit(id, cx)); if self.in_champ_select() { @@ -1432,15 +1482,49 @@ impl Page { /// Computes the cards' order again: for when the home statistics (the champ select's during /// a champ select) or the sort change, and for nothing else. fn reorder(&mut self) { - let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery); - let rows = self - .home_statistics() - .map_or(&[][..], |s| s.rows.as_slice()); - self.order = card_order(rows, sort); + self.order = self.sorted_order(); + } + + /// The cards' order for the home statistics and the sort. + fn sorted_order(&mut self) -> Vec { #[cfg(test)] { self.reorders += 1; } + let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery); + let rows = self + .home_statistics() + .map_or(&[][..], |s| s.rows.as_slice()); + card_order(rows, sort) + } + + /// The pointer left the home grid it held still: the grid prepared when the statistics + /// arrived takes its place, built and sorted already. + fn release_home(&mut self, cx: &mut Context) { + let held = std::mem::take(&mut self.hold_grid); + let Some(next) = self.next_home.take().filter(|_| held) else { + return; + }; + self.order = next.order; + self.home_shown_count = next.count; + self.home_grid.update(cx, |grid, cx| { + grid.set_cards(next.cards, cx); + grid.set_shown(next.shown, cx); + }); + } + + /// The player changed the home's filter or search: the grid follows at once, even under the + /// pointer or with a card kept for its Match. + fn home_filtered(&mut self, cx: &mut Context) { + self.release_home(cx); + self.playback.kept_card = None; + self.refresh_home(cx); + } + + /// The home grid no longer waits for the pointer to leave: what comes next rebuilds it. + fn stop_holding(&mut self) { + self.hold_grid = false; + self.next_home = None; } /// The home statistics' rows in the cards' order: the single iteration the home grid, the @@ -1457,7 +1541,7 @@ impl Page { if self.champion_sort == Some(sort) { return; } - self.hold_grid = false; + self.stop_holding(); self.champion_sort = Some(sort); self.reorder(); if self.in_champ_select() { @@ -1633,20 +1717,42 @@ impl Page { if self.shown_tab != Tab::Challenge || self.in_champ_select() { return; } - // The cards are the rows in the cards' order: a card's index is its position. - let shown: Vec = self - .ordered_rows() - .enumerate() - .filter(|(_, row)| { - self.home_filter.keeps(row) && self.home_search.matches(&row.champion) - }) - .map(|(ix, _)| ix) - .collect(); + if self.hold_grid { + // Nothing moves under the pointer: the grid it leaves for follows instead. + let shown = (self.next_home.as_ref()).map(|next| self.home_shown(&next.order)); + if let (Some(next), Some(shown)) = (self.next_home.as_mut(), shown) { + next.count = shown.len().to_string().into(); + next.shown = shown; + } + return; + } + let shown = self.home_shown(&self.order); self.home_shown_count = shown.len().to_string().into(); self.home_grid .update(cx, |grid, cx| grid.set_shown(shown, cx)); } + /// The cards the home's filter and search keep, as indices of its cards in `order`. The + /// card of a followed Match's champion that was shown stays until its animation ends, so + /// that it changes in place (#89). + fn home_shown(&self, order: &[usize]) -> Vec { + let rows = self + .home_statistics() + .map_or(&[][..], |s| s.rows.as_slice()); + let changing = self.playback.kept_card; + // The cards are the rows in the cards' order: a card's index is its position. + order + .iter() + .filter_map(|&ix| rows.get(ix)) + .enumerate() + .filter(|(_, row)| { + Some(row.champion.id) == changing + || (self.home_filter.keeps(row) && self.home_search.matches(&row.champion)) + }) + .map(|(ix, _)| ix) + .collect() + } + /// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them. fn navigation(&self, cx: &mut Context) -> impl IntoElement { let theme = cx.theme(); @@ -1755,13 +1861,24 @@ impl Render for Page { if animation.finished(now) || cx.reduce_motion() || !self.challenge_visible(window) { self.end_match(cx); } else { - // The comet lands: the splash of the champion just validé settles in. + // The comet lands: the splash of the champion just validé settles in, when it is + // the banner's, the last champion validé. A validation older than the banner's + // (its Match arrived late) leaves the banner as a reload shows it. if animation.has_comet() && animation.since_landing(now) >= 0. && self.playback.previous_banner.take().is_some() { - self.banner_art - .update(cx, |art, cx| art.reveal(self.banner.splash.clone(), cx)); + let last_validated = (self.home_statistics()) + .and_then(|s| s.challenge.as_ref()) + .and_then(|c| c.completion_order.last().copied()); + let splash = self.banner.splash.clone(); + self.banner_art.update(cx, |art, cx| { + if last_validated == Some(animation.champion_id) { + art.reveal(splash, cx); + } else { + art.set_target(splash, cx); + } + }); } window.request_animation_frame(); } @@ -3678,6 +3795,8 @@ mod tests { p.reorders, p.home_grid.read(cx).set_cards_calls, p.ring.read(cx).renders, + // The bouncing crown is the ring's own, moved. + p.ring.read(cx).tessellations.get(), ) }) }; @@ -3733,6 +3852,169 @@ mod tests { assert_eq!(end_state(cx), ended); } + fn home_names(page: &Entity, cx: &mut VisualTestContext) -> Vec { + page.read_with(cx, |p, cx| p.home_grid.read(cx).names()) + } + + /// Frames until the comet of the animation playing lands. + fn until_landed(page: &Entity, cx: &mut VisualTestContext) { + for _ in 0..20 { + frame_after(cx, 100); + if page.read_with(cx, |p, _| p.playback.previous_banner.is_none()) { + return; + } + } + panic!("the comet never landed"); + } + + // The pointer on the grid when a followed Match changes it: the cards change in place, and + // the order, the cards and the filter prepared when the statistics arrive take their place + // once it leaves. Leaving sorts nothing and builds no card (rule #1). + #[gpui::test] + fn leaving_a_grid_a_match_held_still_puts_the_prepared_grid_in_place(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + show( + &page, + cx, + banner_statistics(banner_rows(), vec![2, 1], None), + ); + draw(cx); + settle(cx); + let before = ["Garen", "Ahri", "Zyra", "Lux", "Brand"]; + assert_eq!(home_names(&page, cx), before); + hover(cx, "card-2"); + round_with_matches(&page, cx, &[(2, MatchEnd::Mark, 1)]); + let mut rows = banner_rows(); + rows[1].mastery_points = Some(1000); + statistics_arrive(&page, cx, Some(banner_statistics(rows, vec![2, 1], None))); + draw(cx); + assert_eq!( + home_names(&page, cx), + before, + "the grid moved under the pointer" + ); + let (reorders, prepared) = page.read_with(cx, |p, _| { + ( + p.reorders, + p.next_home.as_ref().map(|next| next.cards.clone()), + ) + }); + let prepared = prepared.expect("nothing was prepared"); + + cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none()); + draw(cx); + + assert_eq!( + home_names(&page, cx), + ["Brand", "Garen", "Ahri", "Zyra", "Lux"] + ); + page.read_with(cx, |p, cx| { + assert_eq!(p.reorders, reorders, "leaving sorted the cards"); + assert!( + Rc::ptr_eq(p.home_grid.read(cx).cards(), &prepared), + "leaving built the cards" + ); + assert!(!p.hold_grid && p.next_home.is_none()); + }); + } + + // « Restants » shown, a champion validé keeps its card until « Validé » has landed on it; + // then the filter leaves it out, as a reload does. + #[gpui::test] + fn a_card_the_filter_leaves_out_stays_until_its_match_has_played(cx: &mut TestAppContext) { + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + let mut rows = banner_rows(); + rows[2] = banner_champion(4, "Garen", 2, None, 900); + show(&page, cx, banner_statistics(rows.clone(), vec![2, 1], None)); + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Remaining; + p.refresh_home(cx); + }); + draw(cx); + assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]); + + round_with_matches(&page, cx, &[(4, MatchEnd::Completed, 1)]); + rows[2] = banner_champion(4, "Garen", 3, Some(on(11, 21)), 900); + statistics_arrive( + &page, + cx, + Some(banner_statistics(rows, vec![2, 1, 4], None)), + ); + draw(cx); + assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]); + until_landed(&page, cx); + assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]); + + for _ in 0..10 { + frame_after(cx, 200); + } + assert!(page.read_with(cx, |p, _| p.playback.animation.is_none())); + assert_eq!(home_names(&page, cx), ["Zyra", "Lux"]); + assert_eq!(page.read_with(cx, |p, _| p.home_shown_count.clone()), "2"); + draw(cx); + assert_at_rest(cx); + + // A card the filter did not show is not added for its Match. + page.update(cx, |p, cx| { + p.home_filter = StateFilter::Completed; + p.home_filtered(cx); + }); + assert_eq!(home_names(&page, cx), ["Garen", "Ahri", "Brand"]); + round_with_matches(&page, cx, &[(3, MatchEnd::Mark, 2)]); + statistics_arrive(&page, cx, None); + draw(cx); + assert_eq!(home_names(&page, cx), ["Garen", "Ahri", "Brand"]); + } + + // The banner shows the last champion validé. The splash of a champion validé settles in when + // it is that one; a validation older than the banner's, whose Match arrived late, leaves the + // banner on the splash a reload shows. + #[gpui::test] + fn only_the_last_champion_validated_settles_into_the_banner(cx: &mut TestAppContext) { + let dir = TestDir::new("banner-late-validation"); + let (page, cx) = open_page_in_season(cx); + let cx = &mut { cx }; + let shown_splash = |cx: &mut VisualTestContext| { + page.read_with(cx, |p, cx| { + let art = p.banner_art.read(cx); + let name = (art.target.as_ref()) + .map(|s| s.path.file_name().unwrap().to_string_lossy().into_owned()); + (name, art.revealing()) + }) + }; + for (order, expected) in [ + (vec![2, 1], ("Ahri.50.30.jpg", true)), + (vec![1, 2], ("Brand.50.30.jpg", false)), + ] { + let mut rows = rows_with_splashes(dir.path()); + rows[0] = ChampionRow { + splash: rows[0].splash.clone(), + ..banner_champion(1, "Ahri", 2, None, 100) + }; + show(&page, cx, banner_statistics(rows, vec![2], None)); + draw(cx); + round_with_matches(&page, cx, &[(1, MatchEnd::Completed, 1)]); + statistics_arrive( + &page, + cx, + Some(banner_statistics( + rows_with_splashes(dir.path()), + order, + None, + )), + ); + draw(cx); + until_landed(&page, cx); + let (name, revealing) = shown_splash(cx); + assert_eq!((name.as_deref(), revealing), (Some(expected.0), expected.1)); + for _ in 0..10 { + frame_after(cx, 200); + } + } + } + #[gpui::test] async fn a_champ_select_that_starts_abandons_the_animation_waiting(app: &mut TestAppContext) { use crate::worker::Msg; @@ -4671,8 +4953,8 @@ mod tests { // The hand gives way when the champ select ends: its lifted card goes at once, and no frame // is asked for a card no longer shown. #[gpui::test] - async fn a_grid_no_longer_shown_asks_for_no_frame(app: &mut TestAppContext) { - let (page, mut window) = page_in_champ_select(app, &frames()[0]).await; + async fn a_grid_no_longer_shown_asks_for_no_frame(cx: &mut TestAppContext) { + let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await; let cx = &mut window; settle(cx); let id = ids(&anvil_cards(&page, cx))[0]; @@ -4688,11 +4970,9 @@ mod tests { ) }); assert_eq!(lifting, (false, 0.)); - // The home comes back with its statistics loading, and a frame is asked for meanwhile - // (#101): once they are shown, nothing is. - app.condition(&page, |p, _| !p.stats_job.running()).await; - draw(cx); - assert_at_rest(cx); + frame_after(cx, 16); + let asked = cx.update(|window, cx| window.simulate_next_frame(cx)); + assert_eq!(asked, 0, "a frame is asked for"); } // As the home grid's test: hovering the cards of « Autres champions » does not draw its grid diff --git a/crates/app/src/page/home.rs b/crates/app/src/page/home.rs index 94a5646..9a429e4 100644 --- a/crates/app/src/page/home.rs +++ b/crates/app/src/page/home.rs @@ -369,7 +369,7 @@ impl Page { .on_click(cx.listener(|this, ix: &usize, _, cx| { if let Some((_, filter)) = FILTERS.get(*ix) { this.home_filter = *filter; - this.refresh_home(cx); + this.home_filtered(cx); cx.notify(); } })), @@ -509,7 +509,9 @@ impl Page { .clone() .cached(StyleRefinement::default().size_full()), ) - .children(animation.map(|a| crate::ring::match_layer(a, a.elapsed(now), cx))), + .children( + animation.map(|a| self.ring.read(cx).match_layer(a, a.elapsed(now), cx)), + ), ) .child(copy) } diff --git a/crates/app/src/ring.rs b/crates/app/src/ring.rs index 9eae6c6..251f168 100644 --- a/crates/app/src/ring.rs +++ b/crates/app/src/ring.rs @@ -183,20 +183,25 @@ impl Geometry { Some((state, dim, 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 { size, ticks, - crown: crown.build().ok(), + crown: crown(frame), } } } +/// The crown of the logo in `frame`. +fn crown(frame: Frame) -> Option> { + 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); + crown.build().ok() +} + /// A copy of `path`, made at the origin, moved `by`. fn moved(path: &Path, by: Point) -> Path { let mut path = path.clone(); @@ -248,6 +253,7 @@ impl Ring { Some(MatchAnimation { start, end, + champion_id: id, index, count: self.ticks.len(), state: self.ticks[index].state, @@ -296,88 +302,109 @@ impl Ring { } } -/// The end of a followed Match, `elapsed` seconds in, over the cached ring: only the moving -/// shapes, a function of the page's render so that the ring is not drawn again (rule #1). The -/// comet and its trail fly from noon to the tick; then the tick flares, gold for a new Mark, -/// bright otherwise, and for a champion Completed the crown bounces. -pub fn match_layer(animation: MatchAnimation, elapsed: f32, cx: &App) -> impl IntoElement { - let theme = cx.theme(); - let (gold, bright, disc) = (theme.primary, theme.foreground, theme.background); - canvas( - |_, _, _| {}, - move |bounds, _, window, _| { - let frame = Frame::of(bounds); - let flight = animation.flight(); - if elapsed < flight { - let arc = TAU * (animation.index as f32 + 0.5) / animation.count as f32 - * ease_out(elapsed / flight); - let radius = (R1 + R2) * 0.5; - let at = - |angle: f32| frame.point(C + radius * angle.sin(), C - radius * angle.cos()); - let mut trail = PathBuilder::stroke(px(4. * frame.scale)); - let tail = (arc - 0.8).max(0.); - trail.move_to(at(tail)); - for i in 1..=12 { - trail.line_to(at(tail + (arc - tail) * i as f32 / 12.)); +impl Ring { + /// The end of a followed Match, `elapsed` seconds in, over the cached ring: only the moving + /// shapes, a function of the page's render so that the ring is not drawn again (rule #1). The + /// comet and its trail fly from noon to the tick; then the tick flares, gold for a new Mark, + /// bright otherwise, and for a champion Completed the crown bounces: the ring's own crown, + /// moved, not tessellated again. + pub fn match_layer( + &self, + animation: MatchAnimation, + elapsed: f32, + cx: &App, + ) -> impl IntoElement { + let theme = cx.theme(); + let (gold, bright, disc) = (theme.primary, theme.foreground, theme.background); + let geometry = self.geometry.clone(); + #[cfg(test)] + let tessellations = self.tessellations.clone(); + canvas( + |_, _, _| {}, + move |bounds, _, window, _| { + let frame = Frame::of(bounds); + let flight = animation.flight(); + if elapsed < flight { + let arc = TAU * (animation.index as f32 + 0.5) / animation.count as f32 + * ease_out(elapsed / flight); + let radius = (R1 + R2) * 0.5; + let at = |angle: f32| { + frame.point(C + radius * angle.sin(), C - radius * angle.cos()) + }; + let mut trail = PathBuilder::stroke(px(4. * frame.scale)); + let tail = (arc - 0.8).max(0.); + trail.move_to(at(tail)); + for i in 1..=12 { + trail.line_to(at(tail + (arc - tail) * i as f32 / 12.)); + } + if let Ok(path) = trail.build() { + window.paint_path(path, gold); + } + let dot = px(8. * frame.scale); + window.paint_quad( + fill( + Bounds::centered_at(at(arc), size(dot * 2., dot * 2.)), + bright, + ) + .corner_radii(dot), + ); + return; } - if let Ok(path) = trail.build() { - window.paint_path(path, gold); - } - let dot = px(8. * frame.scale); - window.paint_quad( - fill( - Bounds::centered_at(at(arc), size(dot * 2., dot * 2.)), - bright, - ) - .corner_radii(dot), + let t = ((elapsed - flight) / MATCH_SETTLE).clamp(0., 1.); + let pulse = (std::f32::consts::PI * t).sin(); + let mut tick = PathBuilder::fill(); + frame.add_tick( + &mut tick, + animation.index, + animation.count, + animation.state, + shape(animation.state).2 + 6. * pulse, ); - return; - } - let t = ((elapsed - flight) / MATCH_SETTLE).clamp(0., 1.); - let pulse = (std::f32::consts::PI * t).sin(); - let mut tick = PathBuilder::fill(); - frame.add_tick( - &mut tick, - animation.index, - animation.count, - animation.state, - shape(animation.state).2 + 6. * pulse, - ); - if let Ok(path) = tick.build() { - let ink = if animation.end == MatchEnd::Mark { - gold - } else { - bright - }; - window.paint_path(path, ink.opacity(pulse)); - } - if animation.has_comet() { - // Cover the resting crown inside the disc, then draw it at its bouncing height. - let radius = px(DISC * frame.scale); - window.paint_quad( - fill( - Bounds::centered_at(frame.point(C, C), size(radius * 2., radius * 2.)), - disc, - ) - .corner_radii(radius), - ); - let rise = 25. * (1. - t).powi(2) * (std::f32::consts::TAU * t).sin(); - let points = CROWN.map(|(x, y)| { - frame.point( - CROWN_AT.0 + x * CROWN_SCALE, - CROWN_AT.1 + y * CROWN_SCALE - rise, - ) - }); - let mut crown = PathBuilder::fill(); - crown.add_polygon(&points, true); - if let Ok(path) = crown.build() { - window.paint_path(path, gold); + if let Ok(path) = tick.build() { + let ink = if animation.end == MatchEnd::Mark { + gold + } else { + bright + }; + window.paint_path(path, ink.opacity(pulse)); } - } - }, - ) - .absolute() - .inset_0() + if animation.has_comet() { + // Cover the resting crown inside the disc, then draw it at its bouncing height. + let radius = px(DISC * frame.scale); + window.paint_quad( + fill( + Bounds::centered_at(frame.point(C, C), size(radius * 2., radius * 2.)), + disc, + ) + .corner_radii(radius), + ); + let rise = 25. * (1. - t).powi(2) * (std::f32::consts::TAU * t).sin(); + let by = bounds.origin - point(px(0.), px(rise * frame.scale)); + // The ring painted its crown at this size, unless the layout just changed. + let geometry = geometry.borrow(); + let made = geometry.as_ref().filter(|g| g.size == bounds.size); + let made_crown; + let crown = match made { + Some(made) => made.crown.as_ref(), + None => { + #[cfg(test)] + tessellations.set(tessellations.get() + 1); + made_crown = crown(Frame::of(Bounds { + origin: Point::default(), + size: bounds.size, + })); + made_crown.as_ref() + } + }; + if let Some(path) = crown { + window.paint_path(moved(path, by), gold); + } + } + }, + ) + .absolute() + .inset_0() + } } impl Render for Ring { diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index ad6b4aa..ab3bdf6 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -21,6 +21,10 @@ pub const RETRY_EVERY_MS: i64 = 20_000; const ADOPT_RETRY_MS: i64 = 60_000; const WAIT_WHILE_PENDING: Duration = Duration::from_millis(RETRY_EVERY_MS as u64); const WAIT_OTHERWISE: Duration = Duration::from_secs(60); +/// How far Riot's clock may be behind the computer's: a game's Match starts no earlier than the +/// last time a round saw the client out of game before it, less this. A Match played before then +/// ended before that time, and started longer ago than this: an Arena game lasts longer. +const CLOCK_SLACK_MS: i64 = 5 * 60_000; /// Why the last update did not (fully) happen. #[derive(Debug, Clone, PartialEq)] @@ -106,6 +110,9 @@ pub struct Status { struct Pending { /// The client's id of that game, when it gave one. game_id: Option, + /// No Match started before this is that game's (`CLOCK_SLACK_MS`); `None` when the app + /// started during that game. + started_after_ms: Option, tries: usize, next_try_ms: i64, } @@ -119,6 +126,8 @@ pub(crate) struct Follow { /// Set when a round's adoption failed: rounds do not try again before. adopt_retry_after_ms: Option, gameflow: Gameflow, + /// The latest round that saw the client out of game. + out_of_game_ms: Option, pending: Vec, /// The Riot ID the app last gave to fall back on when there is nothing else. fallback: Option, @@ -272,12 +281,17 @@ impl Tracker { let known = previous.game_id.is_some() && follow.pending.iter().any(|p| p.game_id == previous.game_id); if ended && !known { + let started_after_ms = follow.out_of_game_ms.map(|ms| ms - CLOCK_SLACK_MS); follow.pending.push(Pending { game_id: previous.game_id, + started_after_ms, tries: 0, next_try_ms: now_ms, }); } + if follow.gameflow.phase != GamePhase::InGame { + follow.out_of_game_ms = Some(now_ms); + } } let account = self.follow().updating.clone(); let mut due: Vec> = (self.follow().pending.iter()) @@ -417,7 +431,8 @@ impl Tracker { } /// A sync whose failure is recorded as the current problem (a success clears it). One that - /// adds a Match ends the waits for the games the client gave no id for. + /// adds a Match ends the waits for the games the client gave no id for whose Match is now + /// stored: one that started after the game's bound, or any without a bound. fn update( &self, account_id: &str, @@ -426,7 +441,12 @@ impl Tracker { match self.sync(account_id, on_progress) { Ok(report) => { if report.added > 0 { - self.follow().pending.retain(|p| p.game_id.is_some()); + let newest = self.latest_start_ms(&report.account.puuid).ok().flatten(); + self.follow().pending.retain(|p| { + p.game_id.is_some() + || p.started_after_ms + .is_some_and(|after| newest.is_none_or(|n| n < after)) + }); } // Riot has just answered for this Account: one more request for its points. self.refresh_mastery(&report.account.puuid); @@ -477,12 +497,19 @@ impl Tracker { let platform = self.platform_of(puuid).ok().flatten(); let Some(match_id) = game_id.zip(platform).map(|(id, p)| format!("{p}_{id}")) else { let newest_before = self.latest_start_ms(puuid).ok().flatten(); + // The earliest bound of the games waiting without an id, if they all have one. + let started_after = (self.follow().pending.iter()) + .filter(|p| p.game_id.is_none()) + .map(|p| p.started_after_ms) + .min() + .flatten(); // Not over: `update` ends the waits without an id, a fetch by id ends the others. let added = self .update(&account_riot_id(account), on_progress) .map_or(0, |report| report.added); if added > 0 - && let Ok(Some(id)) = self.followed_in_sync(puuid, game_id, newest_before) + && let Ok(Some(id)) = + self.followed_in_sync(puuid, game_id, newest_before, started_after) { self.report(puuid, &id, on_match); } @@ -506,13 +533,15 @@ impl Tracker { } /// The followed game among the Matches a sync has just stored: the one with the client's id - /// for it, else the newest Match when it is newer than every Match stored before. Without - /// that id, a first import is only history. + /// for it, else the newest Match when it is newer than every Match stored before and started + /// after the game's bound (`Pending::started_after_ms`): an older Match the sync also brings + /// is history. Without that id nor a bound, a first import is only history. fn followed_in_sync( &self, puuid: &str, game_id: Option, newest_before: Option, + started_after: Option, ) -> Result, Error> { let db = self.db(); let newest = match game_id { @@ -531,8 +560,12 @@ impl Tracker { ), } .optional()?; + let followed = |started: i64| match started_after { + Some(after) => started >= after && newest_before.is_none_or(|b| started > b), + None => newest_before.is_some_and(|b| started > b), + }; Ok(newest - .filter(|(_, started)| game_id.is_some() || newest_before.is_some_and(|b| *started > b)) + .filter(|(_, started)| game_id.is_some() || followed(*started)) .map(|(id, _)| id)) } diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index f375db3..2a87b80 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -32,8 +32,9 @@ fn other_account() -> Account { } /// One Arena 3x6 Match of the recorded Account, placed first with Jinx. -fn new_match(id: &str, hours: i64) -> String { - payload(id, 1750, 222, "Jinx", 1, true, at(date(2026, 4, 5), hours)) +/// A Match started `minutes` after the rounds' clock starts (`now()`): a game the client follows. +fn new_match(id: &str, minutes: i64) -> String { + payload(id, 1750, 222, "Jinx", 1, true, now() + minutes * 60_000) } struct World { @@ -738,7 +739,7 @@ fn a_game_the_client_gave_no_id_for_is_reported_when_a_sync_stores_it() { "Jinx", 6, false, - at(date(2026, 4, 5), 1), + now() + 60_000, )); world.client.set_phase("EndOfGame", true); @@ -754,6 +755,47 @@ fn a_game_the_client_gave_no_id_for_is_reported_when_a_sync_stores_it() { assert!(reported_round(&tracker).is_empty()); } +#[test] +fn an_older_match_a_sync_brings_is_history_and_the_game_without_an_id_still_waits() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + assert!(reported_round(&tracker).is_empty(), "history import"); + world.client.set_game_id(None); + world.client.set_phase("InProgress", true); + assert!(reported_round(&tracker).is_empty()); + // A game played before this one, newer than every Match stored, that Riot lists only now. + world.history.add(payload( + "EUW1_earlier", + 1750, + 11, + "Ahri", + 2, + true, + now() - 30 * 60_000, + )); + world.client.set_phase("EndOfGame", true); + + assert!(reported_round(&tracker).is_empty()); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + + // The followed game's Match, published later, is the one reported. + world.history.add(new_match("EUW1_followed", 1)); + let events = reported_round(&tracker); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 4); + assert_eq!( + events + .iter() + .map(|e| (e.champion_id, e.end)) + .collect::>(), + [(222, MatchEnd::Completed)] + ); + assert_eq!(tracker.status().problem, None); + let calls = world.source_calls(); + assert!(reported_round(&tracker).is_empty()); + assert_eq!(world.source_calls(), calls, "the wait is over"); +} + #[test] fn without_a_platform_the_first_import_reports_only_the_game_the_client_named() { let world = World::new(&[]); diff --git a/docs/performance.md b/docs/performance.md index a62a4ef..cf67775 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -49,7 +49,7 @@ The identity (ring, banner, animations; `docs/interface.md`) follows the same ru - **The foundation** (`crates/app/src/motion.rs`, with the page saying when « Défi » is visible, #86) decides whether the app animates, and when. The Windows setting reaches GPUI's `App::reduce_motion`: gpui-base reads it at start, and the window's own `WM_SETTINGCHANGE` for `SPI_SETCLIENTAREAANIMATION` reads it again, with no polling. When it is off, a tab switch shows its end state at once, and an animation asked for is not played; turning it off ends a transition running and drops the animation waiting, as soon as Windows says so (`AnimationSetting`). An animation asked for while « Défi » is not visible (window minimised or hidden in the notification area, « Statistiques », « Paramètres » or a champ select in front) waits in `Deferred`: only the strongest is kept, it plays once when « Défi » shows again, and a champ select that starts abandons it. - **Tab transitions lay a veil, never move the screen.** A cached view's cache key holds its bounds and its opacity, so fading or sliding the screen itself would draw the grid, the ring and the charts again at every frame and build the cards again. The veil, of the page's background, covers the screen leaving (130 ms) then lifts off the one arriving (280 ms). Each frame is asked for by the transition itself (`on_next_frame`), and none once the veil is lifted. A window hidden during a transition ends it at once. The champion table is a cached view too, laid out by the space the page gives it, so the veil's frames do not draw it. The screen arriving is prepared (its rows copied and sorted, its cards built) only when it is shown, so a switch undone under the veil prepares nothing. Structural tests check that a transition draws neither the grid, the ring nor the table again, builds no card, recomputes no statistics, and asks for no frame at rest. The charts arriving play gpui-kit's own short entry, as after any switch. - **A card hovered is drawn over its grid, which stays cached** (#88). The cards of a grid never change on hover or focus: the page draws the card under the pointer or the keyboard (and those settling back) lifted over the grid, in a deferred layer painted after the page, from where the grid last placed it (`card_lift.rs`). The grid records its visible cards' bounds and indices while it lays out its rows, so drawing them over it reads no layout, searches no card and copies none: the lifted card is the grid's card as it is at each frame. The layer covers each lifted card's place with the page's background, and in the hand lays the veil on the other cards. Each frame is asked for by the page's render while a card moves (`request_animation_frame`), and none once they are still. A wheel drops the grid's lifted cards at once, even at either end of the list, and so does a grid no longer shown (the home under a champ select, the hand after it) or a card filtered out, so no frame is asked for a card no longer drawn; a tab switch or « Paramètres » drops them all, and a hidden window or the setting turned off shows their end state at once. Structural tests check that hovering a card, through its whole animation, draws none of the grid, builds no card and computes no statistics, and that no frame is asked for at rest. A zoomed illustration overflows the card and is cut square by GPUI's rectangular clip: a frame of the page's background rounds its corners again, which nicks the gold glow by a few pixels at each corner. -- **The end of a followed Match is drawn over the cached ring, the cached grid and the banner** (#89). The comet, the flaring tick and the bouncing crown are a function of the page's render in a layer over the ring (`ring::match_layer`): the ring is not drawn again, and these few shapes are built at each frame only while the animation runs, unlike the ring's own, built once per set of ticks. The card that changes is drawn over its grid like a lifted card at rest (`card_lift.rs`). The banner's counter rolls in painted over its place in the title, and the splash of the champion validé settles in with the banner's own decode. The animation is fixed when it starts (tick, duration) and reads no statistics at each frame; each frame is asked for by the page's render while it runs, and none after. Structural tests check that it draws neither the grid nor the ring again, builds no card, recomputes no statistics and asks for no frame at rest. +- **The end of a followed Match is drawn over the cached ring, the cached grid and the banner** (#89). The comet, the flaring tick and the bouncing crown are a function of the page's render in a layer over the ring (`Ring::match_layer`): the ring is not drawn again, and the comet and the tick are built at each frame only while the animation runs, unlike the ring's own shapes, built once per set of ticks; the crown is the ring's own, moved. The card that changes is drawn over its grid like a lifted card at rest (`card_lift.rs`), and stays in the grid until the animation ends even if the filter leaves it out. With the pointer on the grid, nothing moves under it: the grid of the new statistics (order, cards, filter) is prepared when they arrive, and the pointer leaving only puts it in place. The banner's counter rolls in painted over its place in the title, and the splash of the champion validé settles in with the banner's own decode. The animation is fixed when it starts (tick, duration) and reads no statistics at each frame; each frame is asked for by the page's render while it runs, and none after. Structural tests check that it draws neither the grid nor the ring again, tessellates no crown, builds no card, recomputes no statistics and asks for no frame at rest, and that leaving a grid it held still sorts nothing and builds no card. - **Two splashes decoded at most**: the one shown and the one replacing it. All splashes are downloaded in the background, at low priority, after the card portraits, and kept on disk. - During champ select, the Anvil grid is cached at the height of its card rows. The capture replay checks that a splash fade builds no cards and that traversing the hand and « Autres champions » keeps at most two decoded splashes. The latest hovered card takes over when the current fade finishes. - **The ring is a cached view**, laid out from its style alone. A structural test guards it: hovering a card, scrolling the grid or an animation on another part does not render the ring; only a change of what it shows (the champions' state, their order, the selection) or its own animation does. Its gain is checked at the next release benchmark.