Show item and augment names and icons in the recap (#124, #127)

The catalog is loaded from its disk cache at launch and refreshed in the
background when the client appears; unknown ids keep the neutral look.
Provisional Matches get tests for « Provisoire », « En attente » and their
silent publication. Reopening « Parties » no longer re-reads an unchanged
list, and a failed recap is decoded again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nessarandClaude Opus 5.5 committed 2026-11-24 04:25:22 +01:00
1 parent 4c68fd2814
commit 7575ab0165
19 files changed
+990 -49

No files matched your search

+17 -4
View File
@@ -28,8 +28,8 @@ mod worker;
use std::{ops::ControlFlow, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, Preferences, RiotApi, Tracker, data_dir, default_seasons,
load_seasons,
Config, DataDragon, GameData, LeagueClient, Preferences, RiotApi, Tracker, data_dir,
default_seasons, load_seasons,
};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::*;
@@ -54,6 +54,7 @@ struct RootView {
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
game_data: GameData,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
@@ -69,6 +70,7 @@ impl RootView {
fn new(setup: Setup, hidden: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
let Setup {
tracker,
game_data,
riot_id,
notice,
store,
@@ -85,6 +87,7 @@ impl RootView {
notice,
following: !first_launch,
champion_sort,
game_data: Some(game_data.clone()),
},
rx,
tx.clone(),
@@ -100,7 +103,8 @@ impl RootView {
// Nothing is imported before a key exists: the follower starts now.
let (tracker, riot_id) =
(this.tracker.clone(), this.fallback_riot_id.clone());
spawn_follower(tracker, riot_id, this.tx.clone());
let game_data = this.game_data.clone();
spawn_follower(tracker, riot_id, Some(game_data), this.tx.clone());
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
@@ -138,7 +142,12 @@ impl RootView {
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
spawn_follower(
tracker.clone(),
riot_id.clone(),
Some(game_data.clone()),
tx.clone(),
);
Screen::Page
};
if hidden {
@@ -155,6 +164,7 @@ impl RootView {
focus: initial_focus(window, cx),
screen,
tracker,
game_data,
fallback_riot_id: riot_id,
tx,
blank: hidden,
@@ -260,6 +270,8 @@ fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
struct Setup {
tracker: Arc<Tracker>,
/// The cache of the items' and augments' names and icons.
game_data: GameData,
riot_id: String,
notice: Option<String>,
store: KeyStore,
@@ -297,6 +309,7 @@ fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
.with_client(Box::new(LeagueClient::new()));
Ok(Setup {
tracker: Arc::new(tracker),
game_data: GameData::new(dir.join("game-data")),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
+3
View File
@@ -96,6 +96,9 @@ pub struct Launch {
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
/// The cache of the items' and augments' names and icons, read once at launch; none shows
/// the neutral names.
pub game_data: Option<arena_tracker_core::GameData>,
}
/// The page entered or left an Arena champ select.
+50 -6
View File
@@ -18,14 +18,15 @@ pub(in crate::page) use list::MatchRow as Row;
pub use list::init;
use shown::{Champions, ShownRecap};
#[cfg(test)]
pub(in crate::page) use shown::{ShownPlayer, Slot, UNAVAILABLE};
pub(in crate::page) use shown::{PENDING, ShownAugment, ShownPlayer, Slot, UNAVAILABLE};
use super::{Page, Tab};
use crate::card_images::CardImages;
use crate::worker::{MatchEntry, RefreshGate, spawn_match_list, spawn_recap};
use arena_tracker_core::{MatchRecap, Season};
use arena_tracker_core::{GameCatalog, MatchRecap, Season};
use gpui_kit::component::input::InputEvent;
use gpui_kit::*;
use std::sync::Arc;
/// The recap beside the list.
pub(in crate::page) enum Recap {
@@ -70,6 +71,8 @@ pub(in crate::page) struct Matches {
recap_generation: u64,
/// The portraits of the recap, given back when the screen hides.
recap_images: Entity<CardImages>,
/// The names and icons of the items and augments, from the cache on disk.
catalog: Arc<GameCatalog>,
/// In a narrow window, the list is open over the recap.
pub(in crate::page) list_open: bool,
_chosen: Subscription,
@@ -108,6 +111,7 @@ impl Matches {
recap_job: RefreshGate::default(),
recap_generation: 0,
recap_images: CardImages::new(cx),
catalog: Arc::default(),
list_open: false,
_chosen: chosen,
_searched: searched,
@@ -129,6 +133,17 @@ impl Matches {
&self.recap_images
}
#[cfg(test)]
pub(in crate::page) fn recap_generation(&self) -> u64 {
self.recap_generation
}
/// The names and icons the recap is written with.
#[cfg(test)]
pub(in crate::page) fn catalog(&self) -> &GameCatalog {
&self.catalog
}
#[cfg(test)]
pub(in crate::page) fn generation(&self) -> u64 {
self.generation
@@ -226,8 +241,10 @@ impl Page {
/// still being read is dropped, and nothing queued starts.
pub(in crate::page) fn close_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let matches = &mut self.matches;
// The list is read again at the next opening only if it may be out of date: a read cut
// short here, or one that failed. Stored data that changes meanwhile marks it too.
matches.stale |= matches.job.running() || matches.error.is_some();
matches.generation += 1;
matches.stale = true;
matches.selected = None;
matches.recap = Recap::None;
matches.recap_generation += 1;
@@ -277,7 +294,11 @@ impl Page {
.and_then(|id| entries.iter().find(|entry| entry.match_id == *id))
// Published or corrected meanwhile: decoded again.
.is_some_and(|entry| !previous.contains(entry));
if corrected {
// A decoding that failed is tried again as the list is read again.
let failed = matches!(matches.recap, Recap::Failed(_))
&& (matches.selected.as_ref())
.is_some_and(|id| entries.iter().any(|entry| entry.match_id == *id));
if corrected || failed {
self.request_recap();
}
self.dress_matches(cx);
@@ -341,7 +362,9 @@ impl Page {
self.matches.recap = match result {
Ok(Some(recap)) => {
let champions = self.champions();
let shown = ShownRecap::new(&recap, self.chosen_champion(), &champions);
let catalog = self.matches.catalog.clone();
let shown =
ShownRecap::new(&recap, self.chosen_champion(), &champions, &catalog);
let open = match &self.matches.recap {
Recap::Ready {
recap: old, open, ..
@@ -395,10 +418,31 @@ impl Page {
}
let champions = self.champions();
self.refilter(&champions, cx);
self.rewrite_recap(&champions);
}
/// New names and icons for the items and augments: the recap shown is written again.
pub(in crate::page) fn apply_game_data(
&mut self,
catalog: Arc<GameCatalog>,
cx: &mut Context<Self>,
) {
self.matches.catalog = catalog;
// A hidden screen holds no recap: the next one decoded has them.
if matches!(self.matches.recap, Recap::Ready { .. }) {
let champions = self.champions();
self.rewrite_recap(&champions);
cx.notify();
}
}
/// Writes the recap shown again, with the champions and the catalog as they are now.
fn rewrite_recap(&mut self, champions: &Champions) {
let champion = self.chosen_champion();
let champion = (champion.0, champion.1.to_string());
let catalog = self.matches.catalog.clone();
if let Recap::Ready { recap, shown, .. } = &mut self.matches.recap {
**shown = ShownRecap::new(recap, (champion.0, &champion.1), &champions);
**shown = ShownRecap::new(recap, (champion.0, &champion.1), champions, &catalog);
}
}
}
+35 -10
View File
@@ -2,7 +2,7 @@
//! Match chosen, already written (`ShownRecap`), its teams by Placement and one line per
//! player, the Account's in gold. A click or a key on a line unfolds the details of the player.
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _, Theme};
@@ -12,13 +12,14 @@ use gpui_kit::*;
use gpui_kit::base::Button as BaseButton;
use super::details::Details;
use super::shown::{ShownPlayer, ShownRecap, ShownTeam, Slot, Value};
use super::shown::{ShownAugment, ShownPlayer, ShownRecap, ShownTeam, Slot, Value};
use crate::page::Page;
use crate::theme::{gold_ink, heading, surface};
const PORTRAIT: f32 = 32.;
const HEADER_PORTRAIT: f32 = 48.;
const SLOT: f32 = 24.;
const AUGMENT_ICON: f32 = 16.;
fn portrait(path: Option<&PathBuf>, size: f32, theme: &Theme) -> AnyElement {
match path {
@@ -288,15 +289,15 @@ fn items(slots: &Result<[Slot; 7], Value>, player: usize, theme: &Theme) -> AnyE
.border_color(theme.border);
match slot {
Slot::Empty => base,
Slot::Item(title) => {
Slot::Item { title, icon } => {
let title = title.clone();
base.bg(surface(theme))
.tooltip(move |window, cx| Tooltip::new(title.clone()).build(window, cx))
.child(
Icon::new(IconName::Frame)
.xsmall()
.text_color(theme.muted_foreground),
)
.child(match icon {
// The slot's border stays: the icon is a little inside it.
Some(path) => game_icon(path, SLOT - 2.),
None => neutral_icon(theme),
})
}
Slot::Missing => base
.border_dashed()
@@ -306,7 +307,24 @@ fn items(slots: &Result<[Slot; 7], Value>, player: usize, theme: &Theme) -> AnyE
.into_any_element()
}
fn augments(augments: &Result<Vec<SharedString>, Value>, theme: &Theme) -> AnyElement {
/// An icon of the game data, from its file on disk.
fn game_icon(path: &Path, size: f32) -> AnyElement {
img(path.to_path_buf())
.size(px(size))
.flex_shrink_0()
.rounded(px(3.))
.into_any_element()
}
/// What stands for an icon the cache does not hold.
fn neutral_icon(theme: &Theme) -> AnyElement {
Icon::new(IconName::Frame)
.xsmall()
.text_color(theme.muted_foreground)
.into_any_element()
}
fn augments(augments: &Result<Vec<ShownAugment>, Value>, theme: &Theme) -> AnyElement {
let muted = theme.muted_foreground;
match augments.as_deref() {
Err(word) => absent("Améliorations", word, theme),
@@ -321,6 +339,9 @@ fn augments(augments: &Result<Vec<SharedString>, Value>, theme: &Theme) -> AnyEl
.gap_1()
.children(augments.iter().map(|augment| {
div()
.h_flex()
.items_center()
.gap_1()
.px(px(6.))
.py(px(1.))
.rounded(px(6.))
@@ -328,7 +349,11 @@ fn augments(augments: &Result<Vec<SharedString>, Value>, theme: &Theme) -> AnyEl
.border_1()
.border_color(theme.border)
.text_xs()
.child(augment.clone())
.child(match &augment.icon {
Some(path) => game_icon(path, AUGMENT_ICON),
None => neutral_icon(theme),
})
.child(augment.name.clone())
}))
.into_any_element(),
}
+60 -14
View File
@@ -4,7 +4,9 @@
use std::collections::HashMap;
use std::path::PathBuf;
use arena_tracker_core::{Champion, ChampionSearch, MatchRecap, RecapPlayer, Statistics};
use arena_tracker_core::{
Champion, ChampionSearch, GameCatalog, MatchRecap, RecapPlayer, Statistics,
};
use gpui_kit::SharedString;
use super::details::Details;
@@ -101,12 +103,24 @@ impl Value {
pub(in crate::page) enum Slot {
/// The source says the slot is empty (item 0).
Empty,
/// A neutral icon, titled « Objet n » until the items have names.
Item(SharedString),
/// The item's name for its tooltip, and its icon file; none shows the neutral icon (the
/// name is then « Objet n »).
Item {
title: SharedString,
icon: Option<PathBuf>,
},
/// The source does not give this slot.
Missing,
}
/// An augment's chip.
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownAugment {
pub(in crate::page) name: SharedString,
/// None shows the neutral icon.
pub(in crate::page) icon: Option<PathBuf>,
}
#[derive(Clone, Debug, PartialEq)]
pub(in crate::page) struct ShownPlayer {
pub(in crate::page) is_account: bool,
@@ -117,9 +131,9 @@ pub(in crate::page) struct ShownPlayer {
pub(in crate::page) kda: Value,
/// The word for their absence when the source gives no slot at all.
pub(in crate::page) items: Result<[Slot; 7], Value>,
/// « Amélioration n » each; the word for their absence when the source gives no augment
/// field.
pub(in crate::page) augments: Result<Vec<SharedString>, Value>,
/// Each with its name (« Amélioration n » when unknown); the word for their absence when
/// the source gives no augment field.
pub(in crate::page) augments: Result<Vec<ShownAugment>, Value>,
pub(in crate::page) damage: Value,
/// What unfolds under their line.
pub(in crate::page) details: Details,
@@ -148,10 +162,12 @@ pub(in crate::page) struct ShownRecap {
impl ShownRecap {
/// `champion`: the Account's, from its row, should the recap not find the Account.
/// `catalog`: the names and icons of the items and augments.
pub(in crate::page) fn new(
recap: &MatchRecap,
champion: (u32, &str),
champions: &Champions,
catalog: &GameCatalog,
) -> ShownRecap {
let missing = if recap.provisional {
PENDING
@@ -180,7 +196,7 @@ impl ShownRecap {
placement: Value::of(team.placement, missing, ordinal),
account: team.players.iter().any(|p| p.is_account),
players: (team.players.iter())
.map(|p| player(p, missing, champions))
.map(|p| player(p, missing, champions, catalog))
.collect(),
})
.collect(),
@@ -188,7 +204,12 @@ impl ShownRecap {
}
}
fn player(p: &RecapPlayer, missing: &'static str, champions: &Champions) -> ShownPlayer {
fn player(
p: &RecapPlayer,
missing: &'static str,
champions: &Champions,
catalog: &GameCatalog,
) -> ShownPlayer {
let count = |value: Option<u32>| value.map_or_else(|| missing.to_string(), |v| v.to_string());
let kda = [p.kills, p.deaths, p.assists];
let absent = || Value::of(None::<()>, missing, |_| String::new());
@@ -196,7 +217,10 @@ fn player(p: &RecapPlayer, missing: &'static str, champions: &Champions) -> Show
.then(|| {
p.items.map(|slot| match slot {
Some(0) => Slot::Empty,
Some(id) => Slot::Item(format!("Objet {id}").into()),
Some(id) => Slot::Item {
title: catalog.item_name(id).into(),
icon: catalog.item_icon(id),
},
None => Slot::Missing,
})
})
@@ -217,7 +241,10 @@ fn player(p: &RecapPlayer, missing: &'static str, champions: &Champions) -> Show
augments: (p.augments.as_ref())
.map(|augments| {
(augments.iter())
.map(|id| format!("Amélioration {id}").into())
.map(|&id| ShownAugment {
name: catalog.augment_name(id).into(),
icon: catalog.augment_icon(id),
})
.collect()
})
.ok_or_else(absent),
@@ -264,7 +291,12 @@ mod tests {
},
..RecapPlayer::default()
};
let shown = ShownRecap::new(&recap(false, vec![given]), (1, "x"), &Champions::default());
let shown = ShownRecap::new(
&recap(false, vec![given]),
(1, "x"),
&Champions::default(),
&GameCatalog::default(),
);
let team = &shown.teams[0];
assert_eq!(team.placement.text, UNAVAILABLE);
assert!(team.placement.missing && team.account);
@@ -276,7 +308,11 @@ mod tests {
assert_eq!(p.damage.text, "0");
let slots = p.items.as_ref().unwrap();
assert_eq!(slots[0], Slot::Empty);
assert_eq!(slots[1], Slot::Item("Objet 3157".into()));
let unknown = Slot::Item {
title: "Objet 3157".into(),
icon: None,
};
assert_eq!(slots[1], unknown);
assert_eq!(slots[2], Slot::Missing);
assert_eq!(p.augments, Ok(vec![]));
assert!(shown.details.ends_with("Arena 3x6 · Durée : indisponible"));
@@ -290,7 +326,12 @@ mod tests {
champion_name: "Irelia".into(),
..RecapPlayer::default()
};
let shown = ShownRecap::new(&recap(false, vec![bare]), (39, "x"), &Champions::default());
let shown = ShownRecap::new(
&recap(false, vec![bare]),
(39, "x"),
&Champions::default(),
&GameCatalog::default(),
);
let p = &shown.teams[0].players[0];
for value in [&p.riot_id, &p.level, &p.kda, &p.damage] {
assert_eq!((value.text.as_ref(), value.missing), (UNAVAILABLE, true));
@@ -303,7 +344,12 @@ mod tests {
#[test]
fn a_provisional_match_waits_for_its_values() {
let bare = RecapPlayer::default();
let shown = ShownRecap::new(&recap(true, vec![bare]), (39, "x"), &Champions::default());
let shown = ShownRecap::new(
&recap(true, vec![bare]),
(39, "x"),
&Champions::default(),
&GameCatalog::default(),
);
assert!(shown.provisional);
assert_eq!(shown.teams[0].players[0].level.text, PENDING);
assert_eq!(shown.teams[0].placement.text, PENDING);
+5 -1
View File
@@ -9,7 +9,7 @@ use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::AnimationSetting;
use crate::ring::Ring;
use crate::worker::{Msg, RefreshGate};
use crate::worker::{Msg, RefreshGate, spawn_game_catalog};
use arena_tracker_core::{ChampionSearch, SeasonScope, StateFilter, Tracker};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::IndexPath;
@@ -35,6 +35,7 @@ impl Page {
notice,
following,
champion_sort,
game_data,
} = launch;
let season_table = tracker.seasons();
let seasons: Vec<SharedString> = season_table
@@ -86,6 +87,9 @@ impl Page {
let banner_art = BannerArt::new(cx);
let others_hover = Self::light_and_reveal(&others_grid, cx);
let matches = super::matches::Matches::new(&season_table, window, cx);
if let Some(data) = game_data {
spawn_game_catalog(data, tx.clone());
}
let mut subscriptions = Vec::new();
subscriptions.extend(Self::light_on_hover(&home_grid, cx));
+3
View File
@@ -18,6 +18,9 @@ mod matches;
mod matches_details;
mod matches_filters;
mod matches_fixtures;
mod matches_game_data;
mod matches_provisional;
mod matches_refresh;
mod navigation;
mod page_fixtures;
mod portraits;
+10 -4
View File
@@ -8,7 +8,7 @@ use super::page_fixtures::{
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::local_time::local_time;
use crate::page::Tab;
use crate::page::matches::{Recap, Row, ShownPlayer, Slot, UNAVAILABLE};
use crate::page::matches::{Recap, Row, ShownAugment, ShownPlayer, Slot, UNAVAILABLE};
use crate::text::match_time;
use crate::worker::Msg;
use arena_tracker_core::{Champion, ChampionRow};
@@ -147,7 +147,10 @@ async fn the_recap_ranks_the_teams_and_highlights_the_account(cx: &mut TestAppCo
[&me.level, &me.kda, &me.damage].map(|v| v.text.to_string()),
["18", "12 / 2 / 5", "30\u{202f}000"].map(String::from)
);
let item = |id: u32| Slot::Item(SharedString::from(format!("Objet {id}")));
let item = |id: u32| Slot::Item {
title: SharedString::from(format!("Objet {id}")),
icon: None,
};
assert_eq!(
me.items,
Ok([
@@ -160,8 +163,11 @@ async fn the_recap_ranks_the_teams_and_highlights_the_account(cx: &mut TestAppCo
item(3340)
])
);
let augments: Vec<SharedString> = ["Amélioration 101", "Amélioration 212", "Amélioration 305"]
.map(SharedString::from)
let augments: Vec<_> = ["Amélioration 101", "Amélioration 212", "Amélioration 305"]
.map(|name| ShownAugment {
name: name.into(),
icon: None,
})
.to_vec();
assert_eq!(me.augments, Ok(augments));
assert!(cx.debug_bounds("recap-account").is_some());
@@ -0,0 +1,156 @@
//! The names and icons of the items and augments in the recap of « Parties ».
use super::matches_fixtures::{ALICE, open_matches, recap_ready, tracker};
use super::page_fixtures::{center, draw, open_page_launched, switch_tab};
use crate::card_images::tests::TestDir;
use crate::page::matches::{ShownPlayer, Slot};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use crate::worker::game_data::fake::DataClient;
use arena_tracker_core::{GameCatalog, GameData};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
use std::sync::Arc;
/// A cache filled from a client: Rabadon's Deathcap (3089, with its icon) and a named item with
/// none (3020), and the augment 212 with its icon.
fn cache(dir: &TestDir) -> GameData {
let data = GameData::new(dir.path().to_owned());
data.refresh(&DataClient::at("16.22.1"), &mut || {})
.unwrap();
data
}
/// Opens the Match with the full recap (the oldest, third in the list), items 3157, 3089, 3020
/// and 3340 and augments 101, 212 and 305.
async fn open_full_recap(
page: &Entity<Page>,
cx: &mut TestAppContext,
window: &mut VisualTestContext,
) {
let at = center(window, "match-row-2");
window.simulate_click(at, Modifiers::none());
draw(window);
recap_ready(page, cx).await;
draw(window);
}
fn account(page: &Entity<Page>, cx: &mut VisualTestContext) -> ShownPlayer {
page.read_with(cx, |p, _| {
let shown = p.matches.shown().unwrap();
(shown.teams.iter().flat_map(|t| t.players.iter()))
.find(|player| player.is_account)
.unwrap()
.clone()
})
}
fn title_and_icon(slot: &Slot) -> (String, bool) {
match slot {
Slot::Item { title, icon } => (title.to_string(), icon.is_some()),
other => panic!("not an item: {other:?}"),
}
}
fn names(player: &ShownPlayer) -> Vec<(String, bool)> {
player
.augments
.as_ref()
.unwrap()
.iter()
.map(|a| (a.name.to_string(), a.icon.is_some()))
.collect()
}
fn assert_known_names(player: &ShownPlayer) {
let items = player.items.as_ref().unwrap();
assert_eq!(title_and_icon(&items[0]), ("Objet 3157".into(), false));
assert_eq!(
title_and_icon(&items[1]),
("Coiffe de Rabadon".into(), true)
);
assert_eq!(items[2], Slot::Empty);
// Named, without an icon in the cache: the neutral one.
assert_eq!(
title_and_icon(&items[3]),
("Bottes de sorcier".into(), false)
);
assert_eq!(
names(player),
[
("Amélioration 101".to_string(), false),
("Adaptation".to_string(), true),
("Amélioration 305".to_string(), false),
]
);
}
#[gpui::test]
async fn known_ids_show_their_names_and_icons_and_unknown_ones_the_neutral_look(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("recap-game-data");
let data = cache(&dir);
let (page, mut window) = open_page_launched(cx, tracker().0, None, Some(data));
switch_tab(&page, &mut window, Tab::Matches);
// The cache is read at launch, on a worker.
cx.condition(&page, |p, _| !p.matches.catalog().is_empty())
.await;
open_full_recap(&page, cx, &mut window).await;
assert_known_names(&account(&page, &mut window));
}
#[gpui::test]
async fn a_new_catalog_writes_the_recap_shown_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
open_full_recap(&page, cx, &mut window).await;
// No cache yet: today's look.
let me = account(&page, &mut window);
let items = me.items.as_ref().unwrap();
assert_eq!(title_and_icon(&items[1]), ("Objet 3089".into(), false));
assert_eq!(names(&me)[1], ("Amélioration 212".to_string(), false));
let dir = TestDir::new("recap-game-data-later");
let catalog: Arc<GameCatalog> = Arc::new(cache(&dir).load());
window.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(Msg::GameData(catalog), window, cx)
})
});
// The same recap, the same Match, new names.
assert_known_names(&account(&page, &mut window));
assert_eq!(
page.read_with(&window, |p, _| p.matches.selected.clone())
.as_deref(),
Some(ALICE[2])
);
}
#[gpui::test]
async fn the_icons_are_loaded_for_the_recap_and_go_with_the_screen(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("recap-game-icons");
let data = cache(&dir);
let (page, mut window) = open_page_launched(cx, tracker().0, None, Some(data));
switch_tab(&page, &mut window, Tab::Matches);
cx.condition(&page, |p, _| !p.matches.catalog().is_empty())
.await;
open_full_recap(&page, cx, &mut window).await;
window.run_until_parked();
draw(&mut window);
let images = page.read_with(&window, |p, _| p.matches.recap_images().clone());
let held = images.read_with(&window, |images, _| images.held());
let names: Vec<_> = held
.iter()
.filter_map(|path| path.file_name()?.to_str())
.collect();
assert!(names.contains(&"3089.png"), "{names:?}");
assert!(names.contains(&"212.png"), "{names:?}");
switch_tab(&page, &mut window, Tab::Challenge);
assert!(
images
.read_with(&window, |images, _| images.held())
.is_empty()
);
}
@@ -0,0 +1,259 @@
//! A Provisional Match in « Parties »: its badge and its « En attente », and its publication
//! replacing it with the selection and the unfolded player kept.
use super::matches_fixtures::{TwoAccounts, recap_ready};
use super::page_fixtures::{center, draw, open_page_with_tracker, switch_tab};
use crate::page::matches::{PENDING, Recap};
use crate::page::{Page, Tab};
use crate::worker::Msg;
use arena_tracker_core::{
Account, ChampSelect, ClientError, ClientEvent, EndOfGameBlock, GameClientSource, Gameflow,
MatchHistorySource, SourceError, Tracker,
};
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext};
use serde_json::json;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// The game of the Provisional Match, and its Match once Riot publishes it.
const GAME: u64 = 9_000_000_020;
const MATCH: &str = "EUW1_9000000020";
/// When the player left the game: after every Match of the fixtures.
const LEFT_AT_MS: i64 = 1_795_000_000_000;
const RETRY_MS: i64 = 20_000;
/// Alice's history, which publishes the Match of the game once `published`.
struct Publishing {
published: Arc<AtomicBool>,
}
impl MatchHistorySource for Publishing {
fn resolve_account(&self, name: &str, tag: &str) -> Result<Account, SourceError> {
TwoAccounts { more: false }.resolve_account(name, tag)
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
count: usize,
since: Option<i64>,
) -> Result<Vec<String>, SourceError> {
TwoAccounts { more: false }.match_ids(puuid, queue_id, start, count, since)
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
if id != MATCH {
return TwoAccounts { more: false }.fetch_match(id);
}
if !self.published.load(Ordering::SeqCst) {
return Err(SourceError::NotFound);
}
Ok(super::page_fixtures::MATCH_1750
.replace("EUW1_9000000006", MATCH)
.replace("fixture-puuid-self", "Alice"))
}
}
/// Alice in her lobby; the client holds the end-of-game block of the game until a round takes it.
struct Client(Arc<Mutex<Option<EndOfGameBlock>>>);
impl GameClientSource for Client {
fn signed_in(&self) -> Result<(String, String), ClientError> {
Ok(("Alice".into(), "EUW".into()))
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
Ok(Gameflow::default())
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
fn take_end_of_game_block(&self) -> Option<EndOfGameBlock> {
self.0.lock().unwrap().take()
}
}
/// The block of the game: Alice (Irelia) third, among 18 players in 6 teams of 3.
fn block() -> EndOfGameBlock {
let standing = [3, 1, 2, 4, 5, 6];
let players: Vec<_> = (0..18u32)
.map(|i| {
let mine = i == 0;
json!({
"puuid": if mine { "client-alice".to_string() } else { format!("client-{i}") },
"riotIdGameName": if mine { "Alice".to_string() } else { format!("Autre{i}") },
"riotIdTagLine": "EUW",
"championId": if mine { 39 } else { 500 + i },
"subteamId": i / 3 + 1,
"subteamStanding": standing[(i / 3) as usize],
"level": 15,
"kills": i,
"deaths": 2,
"assists": 3,
"items": [3089, 0, 0, 0, 0, 0, 3340],
"augments": [1, 2, 3],
"totalDamageDealtToChampions": 1000 * (i + 1),
})
})
.collect();
let content = json!({
"gameId": GAME,
"gameMode": "CHERRY",
"queueId": 1750,
"gameLength": 1200,
"statsBlock": {"players": players},
});
EndOfGameBlock {
content: content.to_string(),
summoner_puuid: Some("client-alice".into()),
}
}
/// A tracker whose Provisional Match is stored, and the switch that publishes it.
fn tracker_with_provisional() -> (Tracker, Arc<AtomicBool>) {
let published = Arc::new(AtomicBool::new(false));
let held = Arc::new(Mutex::new(None));
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(Publishing {
published: published.clone(),
}),
)
.unwrap()
.with_seasons(Vec::new())
.with_client(Box::new(Client(held.clone())));
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, None, &mut |_| {});
*held.lock().unwrap() = Some(block());
tracker.follow_client(LEFT_AT_MS, None, &mut |_| {});
let stored = tracker.matches("Alice").unwrap();
assert!(stored.iter().any(|m| m.match_id == MATCH && m.provisional));
(tracker, published)
}
fn is_provisional(page: &Entity<Page>, cx: &mut VisualTestContext) -> Option<bool> {
page.read_with(cx, |p, _| match &p.matches.recap {
Recap::Ready { recap, .. } => Some(recap.provisional),
_ => None,
})
}
#[gpui::test]
async fn a_provisional_match_has_its_badge_and_waits_for_its_values(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (tracker, _) = tracker_with_provisional();
let (page, mut window) = open_page_with_tracker(cx, tracker);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
let (first, selected) = page.read_with(&window, |p, cx| {
let rows = p.matches.list.read(cx).rows().to_vec();
(rows[0].clone(), p.matches.selected.clone())
});
assert_eq!(first.match_id, MATCH);
assert!(first.provisional);
assert_eq!(selected.as_deref(), Some(MATCH));
// In the recap header too.
assert!(window.debug_bounds("recap-provisional").is_some());
page.read_with(&window, |p, _| {
let shown = p.matches.shown().unwrap();
assert!(shown.provisional);
// What the block does not give is waited for, never « Indisponible ».
let mut missing = Vec::new();
for team in &shown.teams {
missing.extend(team.placement.missing.then_some(&team.placement));
for player in &team.players {
missing.extend([&player.riot_id, &player.level, &player.damage]);
for group in &player.details.0 {
missing.extend(group.measures.iter().map(|m| &m.value));
}
}
}
let missing: Vec<_> = missing.into_iter().filter(|v| v.missing).collect();
assert!(!missing.is_empty());
assert!(missing.iter().all(|v| v.text == PENDING), "{missing:?}");
});
}
#[gpui::test]
async fn publication_replaces_the_provisional_match_keeping_the_selection_and_the_player_open(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let (tracker, published) = tracker_with_provisional();
let (page, mut window) = open_page_with_tracker(cx, tracker);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
draw(&mut window);
assert_eq!(is_provisional(&page, &mut window), Some(true));
// A player is unfolded.
let at = center(&mut window, "recap-player-1");
window.simulate_click(at, Modifiers::none());
draw(&mut window);
let open = |page: &Entity<Page>, cx: &mut VisualTestContext| {
page.read_with(cx, |p, _| match &p.matches.recap {
Recap::Ready { open, .. } => *open,
_ => None,
})
};
assert_eq!(open(&page, &mut window), Some(1));
// Riot publishes the Match: the follower's round stores it and tells the page.
published.store(true, Ordering::SeqCst);
window.update(|window, cx| {
page.update(cx, |page, cx| {
let changed = page
.tracker
.follow_client(LEFT_AT_MS + 3 * RETRY_MS, None, &mut |_| {});
assert!(changed, "the round says stored data changed");
let status = page.tracker.status();
page.apply(
Msg::Round {
status,
reload: true,
matches: Vec::new(),
},
window,
cx,
);
})
});
cx.condition(
&page,
|p, _| matches!(&p.matches.recap, Recap::Ready { recap, .. } if !recap.provisional),
)
.await;
draw(&mut window);
page.read_with(&window, |p, cx| {
// No switch: the same Match stays chosen, as a published one.
assert_eq!(p.matches.selected.as_deref(), Some(MATCH));
let rows = p.matches.list.read(cx).rows().to_vec();
assert_eq!(rows[0].match_id, MATCH);
assert!(!rows[0].provisional);
assert_eq!(rows.iter().filter(|r| r.match_id == MATCH).count(), 1);
// The published values: Riot's Placement (2nd), nothing waited for.
let shown = p.matches.shown().unwrap();
assert!(!shown.provisional);
let account = shown.teams.iter().find(|t| t.account).unwrap();
assert_eq!(account.placement.text, "2ᵉ");
assert!(shown.teams.iter().all(|t| t.placement.text != PENDING));
});
assert!(window.debug_bounds("recap-provisional").is_none());
assert_eq!(open(&page, &mut window), Some(1));
}
@@ -0,0 +1,108 @@
//! When « Parties » reads again: a list is not read again for nothing, and a recap that failed
//! is decoded again.
use super::matches_fixtures::{ALICE, open_matches, recap_id, recap_ready};
use super::page_fixtures::switch_tab;
use crate::page::Tab;
use crate::page::matches::Recap;
use crate::worker::Msg;
use gpui_kit::TestAppContext;
// The list's `generation` counts the reads asked for: leaving adds one (what is being read is
// dropped), and each reading asked for another.
#[gpui::test]
async fn the_list_is_not_read_again_when_nothing_changed_while_the_screen_was_hidden(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let before = page.read_with(&window, |p, _| p.matches.generation());
switch_tab(&page, &mut window, Tab::Challenge);
switch_tab(&page, &mut window, Tab::Matches);
// No read of the list; the most recent Match is chosen again from the list kept.
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 1
);
assert_eq!(
page.read_with(&window, |p, _| p.matches.selected.clone())
.as_deref(),
Some(ALICE[0])
);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn stored_data_changing_while_hidden_reads_the_list_at_the_next_opening(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_matches(cx).await;
let before = page.read_with(&window, |p, _| p.matches.generation());
switch_tab(&page, &mut window, Tab::Challenge);
window.update(|window, cx| page.update(cx, |page, cx| page.apply(Msg::Champions, window, cx)));
// Hidden: only marked.
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 1
);
switch_tab(&page, &mut window, Tab::Matches);
assert_eq!(
page.read_with(&window, |p, _| p.matches.generation()),
before + 2
);
recap_ready(&page, cx).await;
}
#[gpui::test]
async fn a_list_cut_short_by_leaving_is_read_again_at_the_next_opening(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
window.update(|window, cx| {
page.update(cx, |page, cx| {
let before = page.matches.generation();
// A read is running as the screen leaves: its result is dropped.
page.apply(Msg::Champions, window, cx);
page.close_matches(window, cx);
assert_eq!(page.matches.generation(), before + 2);
page.open_matches(cx);
assert_eq!(page.matches.generation(), before + 3);
})
});
}
/// The recap of the Match chosen fails to decode.
fn fail(page: &gpui_kit::Entity<crate::page::Page>, cx: &mut gpui_kit::VisualTestContext) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let generation = page.matches.recap_generation();
page.apply(
Msg::Recap {
generation,
recap: Box::new(Err("base verrouillée".into())),
},
window,
cx,
);
assert!(matches!(page.matches.recap, Recap::Failed(_)));
})
});
}
#[gpui::test]
async fn a_recap_that_failed_is_decoded_again_when_the_list_is_read_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
fail(&page, &mut window);
window.update(|window, cx| page.update(cx, |page, cx| page.apply(Msg::Champions, window, cx)));
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
#[gpui::test]
async fn a_recap_that_failed_is_decoded_again_when_the_screen_opens_again(cx: &mut TestAppContext) {
let (page, mut window) = open_matches(cx).await;
fail(&page, &mut window);
switch_tab(&page, &mut window, Tab::Challenge);
switch_tab(&page, &mut window, Tab::Matches);
recap_ready(&page, cx).await;
assert_eq!(recap_id(&page, &mut window).as_deref(), Some(ALICE[0]));
}
+13 -2
View File
@@ -4,8 +4,8 @@ use crate::motion::MatchEnd;
use crate::page::{Page, Tab};
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
ChampionState, Charts, Date, FollowedMatch, Format, MatchHistorySource, RiotApi, Season,
SourceError, Statistics, Status, Tracker,
ChampionState, Charts, Date, FollowedMatch, Format, GameData, MatchHistorySource, RiotApi,
Season, SourceError, Statistics, Status, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
@@ -57,6 +57,16 @@ pub(super) fn open_page_with_sort(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
) -> (Entity<Page>, VisualTestContext) {
open_page_launched(cx, tracker, champion_sort, None)
}
/// `game_data`: the cache of the items' and augments' names and icons.
pub(super) fn open_page_launched(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
game_data: Option<GameData>,
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
@@ -80,6 +90,7 @@ pub(super) fn open_page_with_sort(
notice: None,
following: false,
champion_sort,
game_data,
},
rx,
tx,
+1
View File
@@ -12,6 +12,7 @@ impl Page {
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::GameData(catalog) => self.apply_game_data(catalog, cx),
Msg::ChampSelect(champ_select) => {
if self.leave.is_some() {
if champ_select.is_none() {
+3 -1
View File
@@ -1,7 +1,7 @@
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{ChampionSort, Config, RiotApi, Tracker, UpdateChannel};
use arena_tracker_core::{ChampionSort, Config, GameData, RiotApi, Tracker, UpdateChannel};
use gpui_kit::{
AppContext as _, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
VisualTestContext, WindowOptions, point,
@@ -20,6 +20,7 @@ fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
game_data: GameData::new("unused".into()),
riot_id: String::new(),
notice: None,
store: KeyStore::new("unused.toml".into(), config, api),
@@ -100,6 +101,7 @@ fn open_app(
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
game_data: GameData::new("unused".into()),
riot_id: String::new(),
notice: None,
store: KeyStore::new(path.to_path_buf(), config, api),
+29 -4
View File
@@ -4,17 +4,21 @@
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
ChampSelect, ClientEvent, MatchRecap, Scope, Statistics, Status, SyncProgress, Tracker,
UpdateChannel,
ChampSelect, ClientEvent, GameCatalog, GameClientSource, GameData, LeagueClient, MatchRecap,
Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
};
use gpui_kit::base::async_util::Sender;
pub(crate) mod game_data;
mod matches;
pub use game_data::spawn_game_catalog;
use game_data::spawn_game_data_refresh;
pub use matches::{MatchEntry, spawn_match_list, spawn_recap};
/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
@@ -53,6 +57,8 @@ pub enum Msg {
generation: u64,
recap: Box<Result<Option<MatchRecap>, String>>,
},
/// The names and icons of the items and augments, read again from the cache on disk.
GameData(Arc<GameCatalog>),
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
@@ -209,10 +215,16 @@ fn spawn_guarded<T: Send + 'static>(
/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds
/// and a live champ select subscription. Each wake reads the client once and shares that read with
/// both. `fallback_riot_id` is the configured Riot ID.
/// both. `fallback_riot_id` is the configured Riot ID. `game_data`: the cache of the items'
/// and augments' names and icons, brought up to the client's each time the client appears.
/// The champion catalog and portraits are fetched on another thread, so a first launch's
/// import never waits for them.
pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
pub fn spawn_follower(
tracker: Arc<Tracker>,
fallback_riot_id: String,
game_data: Option<GameData>,
tx: Sender<Msg>,
) {
let champions = tracker.clone();
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let mut throttle = Throttle::new(ART_TOLD_EVERY);
@@ -270,7 +282,20 @@ pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sende
let mut previous = None;
let mut snapshot = tracker.client_snapshot();
let mut needs_snapshot = true;
// The game data reads the client on its own connection, not the follower's.
let game_data = game_data.map(|data| {
let client: Arc<dyn GameClientSource> = Arc::new(LeagueClient::new());
(data, client, Arc::new(AtomicBool::new(false)))
});
let mut client_up = false;
while !tx.is_closed() {
// Once at launch if the client is there, then each time it comes back: never on a
// timer.
let up = snapshot.signed_in.is_ok();
if let Some((data, client, running)) = game_data.as_ref().filter(|_| up && !client_up) {
spawn_game_data_refresh(data.clone(), client.clone(), running.clone(), tx.clone());
}
client_up = up;
// The follower round uses the same read as the live champ select: one gameflow
// request per wake, and none for a champ select event.
if needs_snapshot {
+147
View File
@@ -0,0 +1,147 @@
//! The game data of the Match Recaps (names and icons of the items and augments): read from its
//! cache at launch, and brought up to the client's when the client appears. Each is one thread,
//! below normal, that ends by itself: nothing runs at idle (rule #1).
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use arena_tracker_core::{GameClientSource, GameData};
use gpui_kit::base::async_util::Sender;
use super::{Msg, lower_priority, spawn_guarded};
#[cfg(test)]
pub(crate) mod fake;
/// Reads the cache once, for the page to start from: a missing or unreadable cache is an empty
/// catalog, never an error.
pub fn spawn_game_catalog(data: GameData, tx: Sender<Msg>) {
spawn_guarded(tx, Msg::Crashed, move |tx| {
let _ = tx.try_send(Msg::GameData(Arc::new(data.load())));
});
}
/// Brings the cache up to the client's game data, and tells the page each time the cache
/// changed (the names are stored, then the icons are) with the catalog read again. Nothing
/// happens while `client` is not there. A failure leaves the old cache and is not shown: the
/// recaps stay readable with their neutral names.
pub fn refresh_game_data(data: &GameData, client: &dyn GameClientSource, tx: &Sender<Msg>) {
let _ = data.refresh(client, &mut || {
let _ = tx.try_send(Msg::GameData(Arc::new(data.load())));
});
}
/// Starts `refresh_game_data` on its own thread unless a pass is still running: the client
/// that appears again meanwhile has nothing more to ask, the pass resumes what was left.
/// A panic is ignored (the cache is only an embellishment), not shown as a crash.
pub fn spawn_game_data_refresh(
data: GameData,
client: Arc<dyn GameClientSource>,
running: Arc<AtomicBool>,
tx: Sender<Msg>,
) {
if running.swap(true, Ordering::AcqRel) {
return;
}
thread::spawn(move || {
lower_priority();
let _ = catch_unwind(AssertUnwindSafe(|| {
refresh_game_data(&data, client.as_ref(), &tx)
}));
running.store(false, Ordering::Release);
});
}
#[cfg(test)]
mod tests {
use super::fake::DataClient;
use super::*;
use crate::card_images::tests::TestDir;
use gpui_kit::base::async_util::unbounded;
fn catalogs(
rx: &gpui_kit::base::async_util::Receiver<Msg>,
) -> Vec<Arc<arena_tracker_core::GameCatalog>> {
std::iter::from_fn(|| match rx.try_recv() {
Ok(Msg::GameData(catalog)) => Some(catalog),
_ => None,
})
.collect()
}
#[test]
fn a_present_client_fills_the_cache_and_the_page_hears_of_each_change() {
let dir = TestDir::new("game-data");
let data = GameData::new(dir.path().to_owned());
let (tx, rx) = unbounded();
refresh_game_data(&data, &DataClient::at("16.22.1"), &tx);
// The names, then the icons.
let heard = catalogs(&rx);
assert_eq!(heard.len(), 2);
assert_eq!(heard[0].item_name(3089), "Coiffe de Rabadon");
assert_eq!(heard[0].item_icon(3089), None);
assert!(heard[1].item_icon(3089).is_some_and(|path| path.is_file()));
assert_eq!(heard[1].item_icon(3020), None);
assert_eq!(heard[1].augment_name(212), "Adaptation");
}
#[test]
fn a_closed_client_asks_for_nothing_and_leaves_the_cache() {
let dir = TestDir::new("game-data");
let data = GameData::new(dir.path().to_owned());
let (tx, rx) = unbounded();
refresh_game_data(&data, &DataClient::at("16.22.1"), &tx);
catalogs(&rx);
let closed = DataClient::closed();
refresh_game_data(&data, &closed, &tx);
assert!(catalogs(&rx).is_empty());
assert!(closed.asked.lock().unwrap().is_empty());
assert_eq!(data.load().item_name(3089), "Coiffe de Rabadon");
}
#[test]
fn the_same_game_version_is_not_read_again() {
let dir = TestDir::new("game-data");
let data = GameData::new(dir.path().to_owned());
let (tx, rx) = unbounded();
refresh_game_data(&data, &DataClient::at("16.22.1"), &tx);
catalogs(&rx);
let client = DataClient::at("16.22.1");
refresh_game_data(&data, &client, &tx);
assert!(catalogs(&rx).is_empty());
assert!(client.asked.lock().unwrap().is_empty());
}
#[test]
fn the_cache_is_read_at_launch_and_a_missing_one_is_an_empty_catalog() {
let dir = TestDir::new("game-data");
let (tx, rx) = unbounded();
spawn_game_catalog(GameData::new(dir.path().join("absent")), tx.clone());
let Ok(Msg::GameData(catalog)) = gpui_kit::block_on(rx.recv()) else {
panic!("no catalog");
};
assert!(catalog.is_empty());
assert_eq!(catalog.item_name(3089), "Objet 3089");
}
#[test]
fn a_pass_still_running_is_not_started_twice() {
let dir = TestDir::new("game-data");
let (tx, rx) = unbounded();
let running = Arc::new(AtomicBool::new(true));
let client: Arc<dyn GameClientSource> = Arc::new(DataClient::at("16.22.1"));
spawn_game_data_refresh(
GameData::new(dir.path().to_owned()),
client,
running.clone(),
tx,
);
// Nothing started: the sender is gone with no message.
assert!(gpui_kit::block_on(rx.recv()).is_err());
assert!(running.load(Ordering::Acquire));
}
}
+86
View File
@@ -0,0 +1,86 @@
//! A game client that serves game data, for the tests of the worker and of the screens.
use std::sync::Mutex;
use std::time::Duration;
use arena_tracker_core::{ChampSelect, ClientError, ClientEvent, GameClientSource, Gameflow};
use serde_json::json;
/// What the client serves as an icon: only the PNG signature is checked by the cache.
pub(crate) const ICON: &[u8] = b"\x89PNG\r\n\x1a\nfake";
/// A client with the game data of one game version: a few items and augments, in French.
pub(crate) struct DataClient {
version: Option<String>,
/// The routes asked for, in order.
pub(crate) asked: Mutex<Vec<String>>,
}
impl DataClient {
pub(crate) fn at(version: &str) -> DataClient {
DataClient {
version: Some(version.into()),
asked: Mutex::default(),
}
}
/// The client is closed.
pub(crate) fn closed() -> DataClient {
DataClient {
version: None,
asked: Mutex::default(),
}
}
}
impl GameClientSource for DataClient {
fn signed_in(&self) -> Result<(String, String), ClientError> {
Err(ClientError::Absent)
}
fn gameflow(&self) -> Result<Gameflow, ClientError> {
Err(ClientError::Absent)
}
fn official_progress(&self, _: &str) -> Result<Option<u32>, ClientError> {
Ok(None)
}
fn champ_select(&self) -> Result<ChampSelect, ClientError> {
Err(ClientError::Absent)
}
fn wait_for_event(&self, _: Duration) -> ClientEvent {
ClientEvent::Other
}
fn game_version(&self) -> Result<String, ClientError> {
self.version.clone().ok_or(ClientError::Absent)
}
fn game_data(&self, route: &str) -> Result<Vec<u8>, ClientError> {
if self.version.is_none() {
return Err(ClientError::Absent);
}
self.asked.lock().unwrap().push(route.into());
let body = match route {
"/lol-game-data/assets/v1/items.json" => json!([
{"id": 3089, "name": "Coiffe de Rabadon", "iconPath": "/icons/3089.png"},
// Named, but its icon is not served.
{"id": 3020, "name": "Bottes de sorcier", "iconPath": "/icons/missing.png"},
]),
"/lol-game-data/assets/v1/cherry-augments.json" => json!([
{
"id": 212,
"augmentNameId": "ARAM_ADAPt",
"nameTRA": "Adaptation",
"rarity": "kSilver",
"augmentSmallIconPath": "/icons/adapt.png",
},
]),
"/icons/3089.png" | "/icons/adapt.png" => return Ok(ICON.to_vec()),
_ => return Err(ClientError::Other("introuvable".into())),
};
Ok(body.to_string().into_bytes())
}
}