diff --git a/crates/app/src/champion_table.rs b/crates/app/src/champion_table.rs new file mode 100644 index 0000000..bc0f921 --- /dev/null +++ b/crates/app/src/champion_table.rs @@ -0,0 +1,254 @@ +//! The champion table: one row per champion, virtualised by the component. + +use arena_tracker_core::{ChampionRow, Column as SortKey, Date, sort_rows}; +use gpui_kit::component::table::{Column, ColumnSort, TableDelegate, TableState}; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::*; + +use crate::text::{decimal, state_label}; + +struct Spec { + title: &'static str, + key: SortKey, + width: f32, + numeric: bool, +} + +const fn spec(title: &'static str, key: SortKey, width: f32, numeric: bool) -> Spec { + Spec { + title, + key, + width, + numeric, + } +} + +const SPECS: [Spec; 9] = [ + spec("Champion", SortKey::Champion, 220., false), + spec("État", SortKey::State, 110., false), + spec("Parties", SortKey::Matches, 90., true), + spec("Meilleur Placement", SortKey::BestPlacement, 160., true), + spec("Top 1", SortKey::Top1, 80., true), + spec("Victoires", SortKey::Wins, 100., true), + spec("Placement moyen", SortKey::AveragePlacement, 150., true), + spec("Tentatives", SortKey::Attempts, 110., true), + spec("Dernière Partie", SortKey::LastMatch, 150., true), +]; +/// Hidden outside a Season, where there is no Challenge. +const ATTEMPTS: usize = 7; +const PORTRAIT: f32 = 24.; + +pub struct ChampionTable { + rows: Vec, + in_season: bool, + /// The user's choice; `None` means the default for the view. + sort: Option<(SortKey, bool)>, +} + +impl ChampionTable { + pub fn new() -> ChampionTable { + ChampionTable { + rows: Vec::new(), + in_season: false, + sort: None, + } + } + + /// Replaces the rows (already filtered) and keeps them sorted. + pub fn set_rows(&mut self, rows: Vec, in_season: bool) { + self.rows = rows; + self.in_season = in_season; + self.resort(); + } + + /// Column and `descending`. + fn sorted_by(&self) -> (SortKey, bool) { + self.sort + .filter(|(key, _)| self.in_season || *key != SortKey::Attempts) + .unwrap_or(if self.in_season { + (SortKey::Attempts, true) + } else { + (SortKey::Matches, true) + }) + } + + fn resort(&mut self) { + let (key, descending) = self.sorted_by(); + sort_rows(&mut self.rows, key, descending); + } + + fn spec(&self, col_ix: usize) -> &'static Spec { + &SPECS[col_ix + usize::from(!self.in_season && col_ix >= ATTEMPTS)] + } +} + +fn or_dash(value: Option) -> String { + value.map_or_else(|| "-".into(), |v| v.to_string()) +} + +fn cell_text(row: &ChampionRow, key: SortKey) -> String { + match key { + SortKey::State => state_label(row.state).into(), + SortKey::Champion => row.champion.name.clone(), + SortKey::Matches => row.matches.to_string(), + SortKey::BestPlacement => or_dash(row.best_placement), + SortKey::Top1 => row.top1.to_string(), + SortKey::Wins => row.wins.to_string(), + SortKey::AveragePlacement => row.average_placement.map_or("-".into(), |a| decimal(a, 1)), + SortKey::Attempts => or_dash(row.attempts), + SortKey::LastMatch => or_dash(row.last_match_ms.map(Date::from_ms)), + } +} + +impl TableDelegate for ChampionTable { + fn columns_count(&self, _: &App) -> usize { + SPECS.len() - usize::from(!self.in_season) + } + + fn rows_count(&self, _: &App) -> usize { + self.rows.len() + } + + fn column(&self, col_ix: usize, _: &App) -> Column { + let spec = self.spec(col_ix); + let column = Column::new(spec.title, spec.title).width(px(spec.width)); + let column = if spec.numeric { + column.text_right() + } else { + column + }; + let (sorted_key, descending) = self.sorted_by(); + match spec.key { + key if key == sorted_key && descending => column.descending(), + key if key == sorted_key => column.ascending(), + _ => column.sortable(), + } + } + + // The table cycles a header descending, ascending, then back to `Default`: the view's + // default order. + fn perform_sort( + &mut self, + col_ix: usize, + sort: ColumnSort, + _: &mut Window, + cx: &mut Context>, + ) { + let key = self.spec(col_ix).key; + self.sort = match sort { + ColumnSort::Default => None, + ColumnSort::Ascending => Some((key, false)), + ColumnSort::Descending => Some((key, true)), + }; + self.resort(); + cx.notify(); + } + + fn render_td( + &mut self, + row_ix: usize, + col_ix: usize, + _: &mut Window, + cx: &mut Context>, + ) -> impl IntoElement { + let row = &self.rows[row_ix]; + let key = self.spec(col_ix).key; + if key != SortKey::Champion { + return cell_text(row, key).into_any_element(); + } + let portrait = match &row.portrait { + Some(path) => img(path.clone()).size(px(PORTRAIT)).into_any_element(), + None => div() + .size(px(PORTRAIT)) + .bg(cx.theme().border) + .into_any_element(), + }; + div() + .h_flex() + .items_center() + .gap_2() + .child(portrait) + .child(row.champion.name.clone()) + .into_any_element() + } + + fn render_empty( + &mut self, + _: &mut Window, + cx: &mut Context>, + ) -> impl IntoElement { + div() + .size_full() + .flex() + .items_center() + .justify_center() + .text_color(cx.theme().muted_foreground) + .child("Aucun champion à afficher") + } +} + +#[cfg(test)] +mod tests { + use arena_tracker_core::{Champion, ChampionRow, ChampionState}; + + // Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`. + use super::{ATTEMPTS, ChampionTable, SortKey, cell_text}; + + fn row(name: &str) -> ChampionRow { + ChampionRow { + champion: Champion { + id: 1, + key: name.into(), + name: name.into(), + }, + portrait: None, + matches: 0, + best_placement: None, + top1: 0, + wins: 0, + average_placement: None, + last_match_ms: None, + attempts: None, + state: None, + } + } + + #[test] + fn missing_values_show_a_dash() { + let row = row("Ahri"); + for key in [ + SortKey::BestPlacement, + SortKey::AveragePlacement, + SortKey::Attempts, + SortKey::LastMatch, + ] { + assert_eq!(cell_text(&row, key), "-"); + } + assert_eq!(cell_text(&row, SortKey::State), ""); + } + + #[test] + fn values_are_formatted_in_french() { + let row = ChampionRow { + matches: 3, + best_placement: Some(1), + average_placement: Some(2.5), + last_match_ms: Some(1_700_000_000_000), + attempts: Some(2), + state: Some(ChampionState::Completed), + ..row("Ahri") + }; + assert_eq!(cell_text(&row, SortKey::AveragePlacement), "2,5"); + assert_eq!(cell_text(&row, SortKey::LastMatch), "14/11/2023"); + assert_eq!(cell_text(&row, SortKey::Attempts), "2"); + assert_eq!(cell_text(&row, SortKey::State), "Validé"); + } + + #[test] + fn attempts_column_is_hidden_outside_a_season() { + let mut table = ChampionTable::new(); + assert_eq!(table.spec(ATTEMPTS).key, SortKey::LastMatch); + table.set_rows(vec![], true); + assert_eq!(table.spec(ATTEMPTS).key, SortKey::Attempts); + } +} diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index d94cfba..55bbd46 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,21 +1,179 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +mod champion_table; +mod settings; +mod stats_page; +mod text; +mod worker; + +use std::sync::Arc; +use std::sync::mpsc::{self, Sender}; + +use arena_tracker_core::{ + Config, DataDragon, LeagueClient, RiotApi, Tracker, data_dir, default_seasons, load_seasons, +}; use gpui_kit::component::*; use gpui_kit::*; -struct RootView; +use settings::{KeyEvent, KeyForm, KeyStore}; +use stats_page::{PageEvent, StatsPage}; +use worker::{Msg, spawn_follower}; + +#[derive(Clone, Copy, PartialEq)] +enum Screen { + /// True first launch: the key form stands in for the page until a key is saved. + Prompt, + Page, + Settings, +} + +struct RootView { + page: Entity, + form: Entity, + screen: Screen, + tracker: Arc, + /// The configured Riot ID, used when the game client is closed on first launch. + fallback_riot_id: String, + tx: Sender, + _subscriptions: Vec, +} + +impl RootView { + fn new(setup: Setup, window: &mut Window, cx: &mut Context) -> Self { + let Setup { + tracker, + riot_id, + notice, + store, + } = setup; + // Without a key the page still shows what is stored; only a true first launch (no key + // and nothing stored) has nothing to show, so the key form stands in for the page. + let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty(); + let (tx, rx) = mpsc::channel(); + let page = cx.new(|cx| { + StatsPage::new( + tracker.clone(), + notice, + !first_launch, + rx, + tx.clone(), + window, + cx, + ) + }); + let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx)); + let subscriptions = vec![ + cx.subscribe_in( + &page, + window, + |this, _, event: &PageEvent, window, cx| match event { + PageEvent::OpenSettings => { + this.form.update(cx, |form, cx| form.reset(window, cx)); + this.screen = Screen::Settings; + cx.notify(); + } + }, + ), + cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, _, cx| { + match event { + KeyEvent::Saved if this.screen == Screen::Prompt => { + // 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()); + this.page.update(cx, |page, cx| page.following(cx)); + } + KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)), + KeyEvent::Back => {} + } + this.screen = Screen::Page; + cx.notify(); + }), + ]; + let screen = if first_launch { + Screen::Prompt + } else { + spawn_follower(tracker.clone(), riot_id.clone(), tx.clone()); + Screen::Page + }; + RootView { + page, + form, + screen, + tracker, + fallback_riot_id: riot_id, + tx, + _subscriptions: subscriptions, + } + } +} impl Render for RootView { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let content = match self.screen { + Screen::Page => self.page.clone().into_any_element(), + Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(), + }; + div().size_full().child(content) + } +} + +/// Shown instead of the app when the configuration or the database cannot be loaded. +struct Unavailable(Vec); + +impl Render for Unavailable { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { div() .v_flex() .size_full() .items_center() .justify_center() - .child(arena_tracker_core::startup_message()) + .children(self.0.clone()) } } +struct Setup { + tracker: Arc, + riot_id: String, + notice: Option, + store: KeyStore, +} + +/// Loads the configuration and opens the database, or gives the lines to show instead. A +/// missing config file is fine: the app then asks for the key. +fn startup() -> Result> { + let bad_config = |error: String| { + vec![ + format!("Configuration introuvable ou invalide : {error}"), + "Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(), + ] + }; + let dir = + data_dir().ok_or_else(|| bad_config("la variable APPDATA n'est pas définie.".into()))?; + std::fs::create_dir_all(&dir).map_err(|e| bad_config(e.to_string()))?; + let path = dir.join("config.toml"); + let config = Config::load_or_default(&path).map_err(|e| bad_config(e.to_string()))?; + let (seasons, notice) = match load_seasons(&dir.join("seasons.toml")) { + Ok(seasons) => (seasons, None), + Err(e) => ( + default_seasons(), + Some(format!("Table des Saisons invalide : {e}")), + ), + }; + let api = Arc::new(RiotApi::new(config.riot_api_key.clone(), &config.region)); + let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api.clone())) + .map_err(|e| vec![e.to_string()])? + .with_seasons(seasons) + .with_champions(Box::new(DataDragon::new()), dir.join("portraits")) + .with_client(Box::new(LeagueClient::new())); + Ok(Setup { + tracker: Arc::new(tracker), + riot_id: config.riot_id.clone(), + notice, + store: KeyStore::new(path, config, api), + }) +} + fn main() { gpui_kit::application().run(move |cx| { gpui_kit::init(cx); @@ -24,9 +182,22 @@ fn main() { title: Some("Arena Tracker".into()), ..Default::default() }), + window_bounds: Some(WindowBounds::Windowed(Bounds::centered( + None, + size(px(1280.), px(860.)), + cx, + ))), ..Default::default() }; - gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| RootView)) - .expect("Failed to open window"); + match startup() { + Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| { + cx.new(|cx| RootView::new(setup, window, cx)) + }) + .map(drop), + Err(lines) => { + gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Unavailable(lines))).map(drop) + } + } + .expect("Failed to open window"); }); } diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs new file mode 100644 index 0000000..376b4f0 --- /dev/null +++ b/crates/app/src/settings.rs @@ -0,0 +1,184 @@ +//! The Riot API key form: the first-launch prompt and the settings view. + +use std::path::PathBuf; +use std::sync::Arc; + +use arena_tracker_core::{Config, Error, RiotApi}; +use gpui_kit::component::button::{Button, ButtonVariants as _}; +use gpui_kit::component::input::{Input, InputEvent, InputState}; +use gpui_kit::component::{ActiveTheme as _, StyledExt as _}; +use gpui_kit::*; + +const PLACEHOLDER_SAVED: &str = "Clé enregistrée"; +const PLACEHOLDER_EMPTY: &str = "Clé API Riot"; + +/// Where the key lives: the config file, and the running Riot client that uses it. +pub struct KeyStore { + path: PathBuf, + config: Config, + api: Arc, +} + +impl KeyStore { + pub fn new(path: PathBuf, config: Config, api: Arc) -> KeyStore { + KeyStore { path, config, api } + } + + pub fn has_key(&self) -> bool { + !self.config.riot_api_key.is_empty() + } + + /// Writes the key to the config file and hands it to the Riot client, no restart needed. + fn save(&mut self, key: &str) -> Result<(), Error> { + let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string()); + if let Err(e) = self.config.save(&self.path) { + self.config.riot_api_key = previous; + return Err(e); + } + self.api.set_key(key.to_string()); + Ok(()) + } +} + +pub enum KeyEvent { + Saved, + Back, +} + +pub struct KeyForm { + store: KeyStore, + input: Entity, + /// The first-launch prompt (no key and nothing stored yet) has no way back. + first_launch: bool, + error: Option, + _subscription: Subscription, +} + +impl EventEmitter for KeyForm {} + +impl KeyForm { + pub fn new( + store: KeyStore, + first_launch: bool, + window: &mut Window, + cx: &mut Context, + ) -> Self { + let placeholder = if store.has_key() { + PLACEHOLDER_SAVED + } else { + PLACEHOLDER_EMPTY + }; + let input = cx.new(|cx| { + InputState::new(window, cx) + .masked(true) + .placeholder(placeholder) + }); + let subscription = + cx.subscribe_in(&input, window, |this, _, event: &InputEvent, window, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + this.save(window, cx); + } + }); + KeyForm { + first_launch, + store, + input, + error: None, + _subscription: subscription, + } + } + + /// Back to an empty field, as when the form is opened again. + pub fn reset(&mut self, window: &mut Window, cx: &mut Context) { + self.error = None; + self.clear(window, cx); + cx.notify(); + } + + fn clear(&mut self, window: &mut Window, cx: &mut Context) { + let placeholder = if self.store.has_key() { + PLACEHOLDER_SAVED + } else { + PLACEHOLDER_EMPTY + }; + self.input.update(cx, |input, cx| { + input.set_value("", window, cx); + input.set_placeholder(placeholder, window, cx); + }); + } + + fn save(&mut self, window: &mut Window, cx: &mut Context) { + let key = self.input.read(cx).value(); + let key = key.trim(); + if key.is_empty() { + self.error = Some("Saisissez une clé API.".into()); + } else { + match self.store.save(key) { + Ok(()) => { + self.error = None; + self.first_launch = false; + self.clear(window, cx); + cx.emit(KeyEvent::Saved); + } + Err(e) => self.error = Some(format!("Enregistrement impossible : {e}")), + } + } + cx.notify(); + } +} + +impl Render for KeyForm { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let (title, explanation) = if self.first_launch { + ( + "Clé API Riot", + "Une clé API Riot est nécessaire pour importer vos Parties : demandez-en une sur le portail développeur Riot (developer.riotgames.com). Elle reste enregistrée sur cet ordinateur.", + ) + } else { + ( + "Paramètres", + "Saisissez une nouvelle clé API Riot pour remplacer celle qui est enregistrée. Elle reste enregistrée sur cet ordinateur.", + ) + }; + let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger); + let buttons = div() + .h_flex() + .gap_2() + .child( + Button::new("save") + .primary() + .label("Enregistrer") + .on_click(cx.listener(|this, _, window, cx| this.save(window, cx))), + ) + .children((!self.first_launch).then(|| { + Button::new("back") + .label("Retour") + .on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back))) + })); + div() + .size_full() + .flex() + .items_center() + .justify_center() + .child( + div() + .v_flex() + .w(px(520.)) + .gap_3() + .child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ) + .child(div().text_color(muted).child(explanation)) + .child(Input::new(&self.input).mask_toggle()) + .children( + self.error + .clone() + .map(|error| div().text_color(danger).child(error)), + ) + .child(buttons), + ) + } +} diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs new file mode 100644 index 0000000..7bc52b9 --- /dev/null +++ b/crates/app/src/stats_page.rs @@ -0,0 +1,776 @@ +//! The statistics page: banners, Challenge header, charts and champion table for one Account. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +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::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, + 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, +} + +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.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); + }, + ), + ]; + + // The workers' messages arrive on a plain channel; polling it keeps the UI free of + // any extra dependency. + cx.spawn_in(window, async move |this, cx| { + loop { + cx.background_executor() + .timer(Duration::from_millis(100)) + .await; + loop { + match rx.try_recv() { + Ok(msg) => { + 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; + } + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => return, + } + } + } + }) + .detach(); + + 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(), + 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, + }; + 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(window, cx); + } + } + Msg::Champions => self.reload(window, cx), + Msg::Round { status, reload } => { + self.status = status; + self.pending_round = false; + self.progress = None; + self.crashed = false; + if reload { + self.reload(window, cx); + } + } + Msg::Refreshed(status) => { + self.status = status; + self.progress = None; + self.crashed = false; + self.reload(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(); + } + + /// 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)), + ) + } +} diff --git a/crates/app/src/text.rs b/crates/app/src/text.rs new file mode 100644 index 0000000..694bd48 --- /dev/null +++ b/crates/app/src/text.rs @@ -0,0 +1,145 @@ +//! French display helpers shared by the page and the table. + +use arena_tracker_core::{Account, ChampionState, SyncProgress}; + +/// Fixed decimals with a decimal comma: `1,96`. +pub fn decimal(value: f64, digits: usize) -> String { + format!("{value:.digits$}").replace('.', ",") +} + +/// How many Matches are stored, with the singular and the empty case. +pub fn stored(count: usize) -> String { + match count { + 0 => "Aucune Partie enregistrée".into(), + 1 => "1 Partie enregistrée".into(), + n => format!("{n} Parties enregistrées"), + } +} + +pub fn state_label(state: Option) -> &'static str { + match state { + Some(ChampionState::Completed) => "Validé", + Some(ChampionState::InProgress) => "En cours", + Some(ChampionState::NeverPlayed) => "Jamais joué", + None => "", + } +} + +pub const CLIENT_ABSENT: &str = + "Client League of Legends non détecté : affichage des données enregistrées."; +const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne."; + +pub fn riot_id(account: &Account) -> String { + format!("{}#{}", account.game_name, account.tag_line) +} + +/// The discreet line under the Challenge tile. +pub fn official_note(official: u32) -> String { + format!("Progression officielle : {official}") +} + +pub fn official_differs(app: usize, official: u32) -> String { + format!( + "La Progression officielle du jeu indique {official} champions validés, l'application en compte {app} : des Parties manquent peut-être." + ) +} + +/// The sync status line: what is running, else the last failure, else the stored count. +pub fn sync_line( + busy: bool, + progress: Option, + crashed: bool, + stored_count: Option, +) -> String { + match progress { + // A report with nothing to fetch is still the listing. + Some(p) if busy && p.to_fetch > 0 => { + format!("Import en cours : {} / {} Parties", p.fetched, p.to_fetch) + } + _ if busy => "Synchronisation en cours…".into(), + _ if crashed => INTERNAL_ERROR.into(), + _ => stored_count.map(stored).unwrap_or_default(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decimals_use_a_comma() { + assert_eq!(decimal(1.96, 2), "1,96"); + assert_eq!(decimal(3.0, 1), "3,0"); + assert_eq!(decimal(2.0 / 3.0, 1), "0,7"); + } + + #[test] + fn stored_matches_are_pluralised() { + assert_eq!(stored(0), "Aucune Partie enregistrée"); + assert_eq!(stored(1), "1 Partie enregistrée"); + assert_eq!(stored(42), "42 Parties enregistrées"); + } + + #[test] + fn states_have_a_french_label() { + assert_eq!(state_label(Some(ChampionState::Completed)), "Validé"); + assert_eq!(state_label(Some(ChampionState::InProgress)), "En cours"); + assert_eq!(state_label(Some(ChampionState::NeverPlayed)), "Jamais joué"); + assert_eq!(state_label(None), ""); + } + + fn account(name: &str, tag: &str) -> Account { + Account { + puuid: "p".into(), + game_name: name.into(), + tag_line: tag.into(), + } + } + + #[test] + fn riot_ids_join_name_and_tag() { + assert_eq!(riot_id(&account("Joueur", "EUW")), "Joueur#EUW"); + } + + #[test] + fn official_progress_texts() { + assert_eq!(official_note(52), "Progression officielle : 52"); + assert_eq!( + official_differs(50, 52), + "La Progression officielle du jeu indique 52 champions validés, l'application en compte 50 : des Parties manquent peut-être." + ); + } + + #[test] + fn the_sync_line_follows_what_is_running() { + let progress = SyncProgress { + fetched: 3, + to_fetch: 10, + }; + assert_eq!( + sync_line(true, Some(progress), false, Some(5)), + "Import en cours : 3 / 10 Parties" + ); + assert_eq!( + sync_line(true, None, false, Some(5)), + "Synchronisation en cours…" + ); + let nothing = SyncProgress { + fetched: 0, + to_fetch: 0, + }; + assert_eq!( + sync_line(true, Some(nothing), false, Some(5)), + "Synchronisation en cours…" + ); + assert_eq!( + sync_line(false, None, true, Some(5)), + "Mise à jour impossible : erreur interne." + ); + assert_eq!( + sync_line(false, None, false, Some(1)), + "1 Partie enregistrée" + ); + assert_eq!(sync_line(false, None, false, None), ""); + } +} diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs new file mode 100644 index 0000000..87e4db3 --- /dev/null +++ b/crates/app/src/worker.rs @@ -0,0 +1,142 @@ +//! Background threads: following the game client, and the refresh button. +//! Both talk to the page through `Msg`. + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::Arc; +use std::sync::mpsc::Sender; +use std::thread; +use std::time::{SystemTime, UNIX_EPOCH}; + +use arena_tracker_core::{Status, SyncProgress, Tracker}; + +pub enum Msg { + /// A sync is fetching Matches. + Progress(SyncProgress), + /// The champion catalog and portraits were refreshed. + Champions, + /// A follower round ended; `reload` when the stored data may have changed. + Round { status: Status, reload: bool }, + /// A refresh ended. + Refreshed(Status), + /// A worker thread panicked. + Crashed, +} + +/// At most one refresh thread at a time. A request made while one runs is served once, when it +/// reports back: the sync it was waiting for may have started before the reason for it. +#[derive(Default)] +pub struct RefreshGate { + running: bool, + queued: bool, +} + +impl RefreshGate { + pub fn running(&self) -> bool { + self.running + } + + /// True when a refresh thread must start now. + pub fn request(&mut self) -> bool { + if self.running { + self.queued = true; + return false; + } + self.running = true; + true + } + + /// The running refresh reported back; true when the queued one must start now. + pub fn finished(&mut self) -> bool { + self.running = std::mem::take(&mut self.queued); + self.running + } + + /// A thread panicked: nothing is known to run any more. + pub fn reset(&mut self) { + *self = RefreshGate::default(); + } +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64) +} + +/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting. +fn spawn_guarded(tx: Sender, body: impl FnOnce(&Sender) + Send + 'static) { + thread::spawn(move || { + if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() { + let _ = tx.send(Msg::Crashed); + } + }); +} + +/// Keeps the active Account up to date for as long as the app runs: one thread, rounds of +/// `follow_client` separated by `wait_for_client`. `fallback_riot_id` is the configured Riot ID. +/// 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, fallback_riot_id: String, tx: Sender) { + let champions = tracker.clone(); + spawn_guarded(tx.clone(), move |tx| { + let _ = champions.refresh_champions(); + let _ = tx.send(Msg::Champions); + }); + spawn_guarded(tx, move |tx| { + let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty()); + let mut first = true; + loop { + let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| { + let _ = tx.send(Msg::Progress(progress)); + }); + let status = tracker.status(); + let _ = tx.send(Msg::Round { + status, + reload: changed || first, + }); + first = false; + tracker.wait_for_client(); + } + }); +} + +/// The refresh button: one sync of the Account being kept up to date. +pub fn spawn_refresh(tracker: Arc, tx: Sender) { + spawn_guarded(tx, move |tx| { + // A failure is recorded in the status, which the page shows as a banner. + let _ = tracker.refresh(&mut |progress| { + let _ = tx.send(Msg::Progress(progress)); + }); + let _ = tx.send(Msg::Refreshed(tracker.status())); + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() { + let mut gate = RefreshGate::default(); + assert!(gate.request()); + assert!(gate.running()); + assert!(!gate.request()); + assert!(!gate.request()); + // The running one ends: one queued refresh starts, however many were asked. + assert!(gate.finished()); + assert!(gate.running()); + assert!(!gate.finished()); + assert!(!gate.running()); + assert!(gate.request()); + } + + #[test] + fn a_crash_forgets_the_queue() { + let mut gate = RefreshGate::default(); + assert!(gate.request()); + assert!(!gate.request()); + gate.reset(); + assert!(!gate.running()); + assert!(!gate.finished()); + } +}