//! The statistics page: banners, Challenge header, charts and champion table for one Account. use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ Account, ChallengeSummary, Charts, Format, ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, }; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; use gpui_kit::component::alert::Alert; use gpui_kit::component::button::Button; use gpui_kit::component::chart::{AreaChart, BarChart}; use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState}; use gpui_kit::component::tab::{Tab, TabBar}; use gpui_kit::component::table::{DataTable, TableState}; use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _}; use gpui_kit::*; use crate::champion_table::ChampionTable; use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line}; use crate::worker::{Msg, RefreshGate, spawn_refresh}; const ALL_SEASONS: &str = "Toutes les Saisons"; const ALL_FORMATS: &str = "Tous les Formats"; const NO_MATCH: &str = "Aucune Partie"; const CHART_HEIGHT: f32 = 150.; /// While an import runs, the page is recomputed at most this often. const RELOAD_EVERY: Duration = Duration::from_secs(1); pub enum PageEvent { OpenSettings, } /// One Account in the selector; its value is the puuid. #[derive(Clone, PartialEq)] struct AccountItem { puuid: String, title: SharedString, } impl SelectItem for AccountItem { type Value = String; fn title(&self) -> SharedString { self.title.clone() } fn value(&self) -> &String { &self.puuid } } pub struct StatsPage { tracker: Arc, tx: Sender, notice: Option, /// As of the last follower round or refresh. status: Status, accounts: Vec, last_active: Option, /// The Account the user picked instead of following the one being updated. pinned: Option, /// The Account whose statistics are in `stats`. shown: Option, progress: Option, refresh: RefreshGate, /// Until the follower's first round ends. pending_round: bool, crashed: bool, last_reload: Instant, reload_when_shown: bool, current_season: Option, season: SeasonScope, format: Option, filter: StateFilter, stats: Option, stats_error: Option, stored: Option, account_select: Entity>>, account_items: Vec, season_select: Entity>>, format_select: Entity>>, format_names: Vec, table: Entity>, table_in_season: bool, _subscriptions: Vec, _listener: Task<()>, } impl EventEmitter for StatsPage {} /// The state filters on offer: the Challenge ones only make sense in a Season. fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] { const SEASON: [(&str, StateFilter); 4] = [ ("Tous", StateFilter::All), ("Validés", StateFilter::Completed), ("Restants", StateFilter::Remaining), ("Jamais joués", StateFilter::NeverPlayed), ]; if in_season { &SEASON } else { &[SEASON[0], SEASON[3]] } } impl StatsPage { /// `following`: a follower thread is already running, its first round is pending. pub fn new( tracker: Arc, notice: Option, following: bool, rx: Receiver, tx: Sender, window: &mut Window, cx: &mut Context, ) -> Self { let seasons: Vec = tracker .seasons() .into_iter() .rev() .map(|s| s.name.into()) .chain([ALL_SEASONS.into()]) .collect(); let now_ms = SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_millis() as i64); let current_season = tracker.current_season(now_ms).map(|s| s.name); let season = current_season .clone() .map_or(SeasonScope::AllSeasons, SeasonScope::Season); let selected = match &season { SeasonScope::Season(name) => seasons.iter().position(|s| s.as_ref() == name.as_str()), SeasonScope::AllSeasons => Some(seasons.len() - 1), }; let account_select = cx.new(|cx| SelectState::new(Vec::::new(), None, window, cx)); let season_select = cx.new(|cx| SelectState::new(seasons, selected.map(IndexPath::new), window, cx)); let format_names = vec![SharedString::from(ALL_FORMATS)]; let format_select = cx .new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx)); let table = cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false)); let subscriptions = vec![ cx.observe_window_visibility(window, |this, visibility, window, cx| { if visibility.is_visible() && this.reload_when_shown { this.reload_when_shown = false; this.reload(window, cx); cx.notify(); } }), cx.subscribe_in( &account_select, window, |this, _, event: &SelectEvent>, window, cx| { let SelectEvent::Confirm(Some(puuid)) = event else { return; }; // Picking the Account being updated is following it again. let following = this .status .updating .as_ref() .is_some_and(|a| a.puuid == *puuid); this.pinned = (!following).then(|| puuid.clone()); this.reload(window, cx); }, ), cx.subscribe_in( &season_select, window, |this, _, event: &SelectEvent>, window, cx| { let SelectEvent::Confirm(Some(name)) = event else { return; }; this.season = if name.as_ref() == ALL_SEASONS { SeasonScope::AllSeasons } else { SeasonScope::Season(name.to_string()) }; this.recompute(window, cx); }, ), cx.subscribe_in( &format_select, window, |this, _, event: &SelectEvent>, window, cx| { let SelectEvent::Confirm(Some(name)) = event else { return; }; let formats = this.stats.iter().flat_map(|s| s.formats.iter()); this.format = formats.copied().find(|f| f.name() == name.as_ref()); this.recompute(window, cx); }, ), ]; // gpui-kit's async channel wakes the page on sends, with no timer or extra dependency. let listener = cx.spawn_in(window, async move |this, cx| { while let Ok(msg) = rx.recv().await { let applied = cx .update(|window, app| this.update(app, |page, cx| page.apply(msg, window, cx))); // The window or the page is gone: nothing left to update. if !matches!(applied, Ok(Ok(()))) { return; } } }); let mut page = StatsPage { status: tracker.status(), tracker, tx, notice, accounts: Vec::new(), last_active: None, pinned: None, shown: None, progress: None, refresh: RefreshGate::default(), pending_round: following, crashed: false, last_reload: Instant::now(), reload_when_shown: false, current_season, season, format: None, filter: StateFilter::All, stats: None, stats_error: None, stored: None, account_select, account_items: Vec::new(), season_select, format_select, format_names, table, table_in_season: false, _subscriptions: subscriptions, _listener: listener, }; page.reload(window, cx); page } /// The follower thread was just started. pub fn following(&mut self, cx: &mut Context) { self.pending_round = true; cx.notify(); } /// Starts a refresh, or queues one behind the refresh already running. pub fn begin_refresh(&mut self, cx: &mut Context) { if self.refresh.request() { spawn_refresh(self.tracker.clone(), self.tx.clone()); } cx.notify(); } fn busy(&self) -> bool { self.progress.is_some() || self.refresh.running() || self.pending_round } /// The Account shown: the pinned one, else the one being updated. fn viewed(&self) -> Option<&Account> { self.pinned .as_ref() .and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid)) .or(self.status.updating.as_ref()) .or(self.last_active.as_ref()) .or(self.accounts.first()) } /// Whether the Account shown is not the one being updated (or none is), so only stored /// data is shown. Unknown until the follower's first round has reported. fn stale(&self) -> bool { !self.pending_round && self.viewed().is_some_and(|viewed| { self.status .updating .as_ref() .is_none_or(|updating| updating.puuid != viewed.puuid) }) } /// The game's own count, only meaningful for the Account being updated in the current Season. fn official(&self) -> Option<&ProgressCheck> { let updated = matches!((self.viewed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid); let current = matches!((&self.season, &self.current_season), (SeasonScope::Season(s), Some(c)) if s == c); (updated && current).then_some(&self.status.official_progress) } fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context) { match msg { Msg::Progress(progress) => { self.progress = Some(progress); if self.last_reload.elapsed() >= RELOAD_EVERY { self.reload_if_shown(window, cx); } } Msg::Champions => self.reload_if_shown(window, cx), Msg::Round { status, reload } => { // A follower round that changes nothing shown must not rebuild the page (they keep coming). let unchanged = status == self.status && !reload && !self.pending_round && self.progress.is_none() && !self.crashed; if unchanged { return; } self.status = status; self.pending_round = false; self.progress = None; self.crashed = false; if reload { self.reload_if_shown(window, cx); } } Msg::Refreshed(status) => { self.status = status; self.progress = None; self.crashed = false; self.reload_if_shown(window, cx); // A request made while this one ran (a key saved meanwhile) is served now. if self.refresh.finished() { spawn_refresh(self.tracker.clone(), self.tx.clone()); } } Msg::Crashed => { self.refresh.reset(); self.pending_round = false; self.progress = None; self.crashed = true; } } cx.notify(); } /// A worker's reload, deferred while GPUI reports the window hidden (minimised or not shown; /// on Windows a covered window still counts as visible), then run as soon as it is shown again /// (rule #1, budget 3). fn reload_if_shown(&mut self, window: &mut Window, cx: &mut Context) { if window.is_visible() { self.reload(window, cx); } else { self.reload_when_shown = true; } } /// Re-reads the Accounts, then the statistics of the one shown. fn reload(&mut self, window: &mut Window, cx: &mut Context) { self.accounts = self.tracker.accounts().unwrap_or_default(); self.last_active = self.tracker.last_active_account().ok().flatten(); if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) { self.pinned = None; } let items: Vec = self .accounts .iter() .map(|a| AccountItem { puuid: a.puuid.clone(), title: riot_id(a).into(), }) .collect(); let changed = items != self.account_items; self.account_items = items.clone(); let viewed = self.viewed().map(|a| a.puuid.clone()); self.account_select.update(cx, |select, cx| { if changed { select.set_items(items, window, cx); } if let Some(puuid) = &viewed && select.selected_value() != Some(puuid) { select.set_selected_value(puuid, window, cx); } }); self.recompute(window, cx); } /// Recomputes the statistics for the current scope; never called while rendering. fn recompute(&mut self, window: &mut Window, cx: &mut Context) { self.last_reload = Instant::now(); if matches!(self.season, SeasonScope::AllSeasons) && !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed) { self.filter = StateFilter::All; } let viewed = self.viewed().map(|a| a.puuid.clone()); if viewed != self.shown { // Another Account may not have played the selected Format. self.shown = viewed.clone(); if self.format.take().is_some() { self.format_select.update(cx, |select, cx| { select.set_selected_index(Some(IndexPath::new(0)), window, cx) }); } } self.stats = None; self.stats_error = None; self.stored = None; if let Some(puuid) = &viewed { let scope = Scope { season: self.season.clone(), format: self.format, }; match self.tracker.statistics(puuid, &scope) { Ok(stats) => self.stats = Some(stats), Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")), } self.stored = self.tracker.match_count(puuid).ok(); } let mut names = vec![SharedString::from(ALL_FORMATS)]; names.extend( self.stats .iter() .flat_map(|s| s.formats.iter().map(|f| SharedString::from(f.name()))), ); if names != self.format_names { self.format_names = names.clone(); self.format_select .update(cx, |select, cx| select.set_items(names, window, cx)); } self.refresh_table(cx); cx.notify(); } fn refresh_table(&mut self, cx: &mut Context) { let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows.filter(|row| self.filter.keeps(row)).cloned().collect(); let in_season = matches!(self.season, SeasonScope::Season(_)); // Only a change of columns needs `refresh`, which also resets the column widths. let columns_changed = in_season != self.table_in_season; self.table_in_season = in_season; self.table.update(cx, |table, cx| { table.delegate_mut().set_rows(rows, in_season); if columns_changed { table.refresh(cx); } cx.notify(); }); } /// One line each, the most important first; the stored data stays visible under all. fn banners(&self) -> Vec { let mut banners = Vec::new(); if let Some(problem) = &self.status.problem { let message = problem.message(); banners.push(match problem { UpdateProblem::MatchPending | UpdateProblem::RateLimited | UpdateProblem::NoAccount => Alert::warning("problem", message), _ => Alert::error("problem", message), }); } if let Some(ProgressCheck::Differs { app, official }) = self.official() { banners.push(Alert::warning( "official", official_differs(*app, *official), )); } if !self.pending_round && !self.status.client_running { banners.push(Alert::info("client", CLIENT_ABSENT)); } if let Some(notice) = &self.notice { banners.push(Alert::warning("notice", notice.clone())); } if let Some(error) = &self.stats_error { banners.push(Alert::error("stats", error.clone())); } banners .into_iter() .map(|alert| alert.small().into_any_element()) .collect() } } fn tile( label: &'static str, value: String, note: Option, border: Hsla, muted: Hsla, ) -> impl IntoElement { div() .v_flex() .flex_1() .gap_1() .p_3() .border_1() .border_color(border) .rounded_md() .child(div().text_sm().text_color(muted).child(label)) .child( div() .text_xl() .font_weight(FontWeight::SEMIBOLD) .child(value), ) .children(note.map(|note| div().text_xs().text_color(muted).child(note))) } fn challenge_tiles( c: &ChallengeSummary, official: Option<&ProgressCheck>, border: Hsla, muted: Hsla, ) -> impl IntoElement { let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2)); // Next to the count whether the app agrees or not; the banner covers the difference. let note = match official { Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => { Some(official_note(*n)) } _ => None, }; div() .h_flex() .gap_3() .child(tile( "Champions validés", format!("{} / {}", c.completed, c.total), note, border, muted, )) .child(tile( "Tentatives", c.attempts.to_string(), None, border, muted, )) .child(tile( "Tentatives par champion validé", average, None, border, muted, )) .child(tile( "Du premier coup", c.first_tries.to_string(), None, border, muted, )) } /// A titled card holding a chart, or `empty` in its place. fn card( title: &'static str, chart: Option, empty: &'static str, border: Hsla, muted: Hsla, ) -> impl IntoElement { let body = chart.unwrap_or_else(|| { div() .size_full() .flex() .items_center() .justify_center() .text_color(muted) .child(empty) .into_any_element() }); div() .v_flex() .flex_1() .min_w_0() .gap_2() .p_3() .border_1() .border_color(border) .rounded_md() .child( div() .text_sm() .font_weight(FontWeight::SEMIBOLD) .child(title), ) .child(div().h(px(CHART_HEIGHT)).w_full().children(Some(body))) } fn placements_chart(charts: &Charts) -> Option { (!charts.placements.is_empty()).then(|| { BarChart::new(charts.placements.clone()) .id("placements") .band(|(placement, _)| placement.to_string()) .value(|(_, count)| *count as f64) .label(|(_, count)| count.to_string()) .name("Parties") .into_any_element() }) } fn completed_chart(charts: &Charts) -> Option { let points: Vec<(String, f64)> = charts .completed_over_time .iter() .map(|(day, count)| (day.to_string(), *count as f64)) .collect(); // The counts only grow, so the last one is the highest. The y axis runs from 0 to a // multiple of 4 in four steps with no padding: every tick is then a whole number. let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n); let top = top.div_ceil(4).max(1) * 4; (!points.is_empty()).then(|| { AreaChart::new(points) .id("completed") .x(|(day, _)| day.clone()) .y(|(_, count)| *count) .linear() .x_tick_count(3) .y_axis(true) .y_domain(0., top as f64) .y_padding(0., 0.) .y_tick_count(5) .name("Champions validés") .into_any_element() }) } fn attempts_chart(charts: &Charts) -> Option { const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"]; let bars: Vec<(&str, usize)> = LABELS .into_iter() .zip(charts.attempts_to_complete) .collect(); bars.iter().any(|(_, count)| *count > 0).then(|| { BarChart::new(bars) .id("attempts") .band(|(label, _)| *label) .value(|(_, count)| *count as f64) .label(|(_, count)| count.to_string()) .name("Champions") .into_any_element() }) } impl Render for StatsPage { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let (border, muted) = { let theme = cx.theme(); (theme.border, theme.muted_foreground) }; let in_season = matches!(self.season, SeasonScope::Season(_)); let options = filters(in_season); let selected = options.iter().position(|(_, f)| *f == self.filter); let empty = Charts { placements: vec![], completed_over_time: vec![], attempts_to_complete: [0; 5], }; let charts = self.stats.as_ref().map_or(&empty, |s| &s.charts); let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref()); let mut cards = vec![ card( "Répartition des Placements", placements_chart(charts), NO_MATCH, border, muted, ) .into_any_element(), ]; if in_season { cards.push( card( "Champions validés au fil de la Saison", completed_chart(charts), "Aucun champion validé", border, muted, ) .into_any_element(), ); cards.push( card( "Tentatives pour valider", attempts_chart(charts), "Aucun champion validé", border, muted, ) .into_any_element(), ); } let busy = self.busy(); let status_line = sync_line(busy, self.progress, self.crashed, self.stored); div() .v_flex() .size_full() .gap_3() .p_3() .child( // The selectors give way first (down to their minimum width), then the buttons // wrap onto a second line: nothing is ever clipped. div() .h_flex() .flex_wrap() .items_center() .justify_between() .gap_x_3() .gap_y_2() .child( div() .h_flex() .items_center() .gap_3() .min_w_0() .child( Select::new(&self.account_select) .id("account") .placeholder("Aucun Compte") .w(px(260.)) .min_w(px(150.)), ) .children(self.stale().then(|| { div() .text_sm() .whitespace_nowrap() .text_color(muted) .child("Non mis à jour") })) .child( Select::new(&self.season_select) .id("season") .w(px(220.)) .min_w(px(130.)), ) .child( Select::new(&self.format_select) .id("format") .w(px(220.)) .min_w(px(130.)), ), ) .child( div() .h_flex() .items_center() .gap_3() .flex_shrink_0() .child( div() .text_sm() .whitespace_nowrap() .text_color(muted) .child(status_line), ) .child( Button::new("refresh") .label("Actualiser") .disabled(busy) .on_click(cx.listener(|this, _, _, cx| this.begin_refresh(cx))), ) .child(Button::new("settings").label("Paramètres").on_click( cx.listener(|_, _, _, cx| cx.emit(PageEvent::OpenSettings)), )), ), ) .child(div().v_flex().gap_1().children(self.banners())) .children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted))) .child(div().h_flex().gap_3().children(cards)) .child( TabBar::new("state-filter") .segmented() .selected_index(selected.unwrap_or(0)) .children(options.iter().map(|(label, _)| Tab::new().label(*label))) .on_click(cx.listener(|this, ix: &usize, _, cx| { let in_season = matches!(this.season, SeasonScope::Season(_)); if let Some((_, filter)) = filters(in_season).get(*ix) { this.filter = *filter; this.refresh_table(cx); cx.notify(); } })), ) .child( div() .flex_1() .min_h(px(240.)) .child(DataTable::new(&self.table).stripe(true)), ) } }