Files
arena-tracker/crates/app/src/main.rs
T
nessarandClaude Opus 5.5 d601d30605 Delete an Account or a Friend from « Paramètres » (#117)
- New « Comptes » section in the settings (settings/accounts.rs): your Accounts then your
  Friends, each with « Supprimer », an inline confirmation with the count of stored Matches and
  the client-only sentence, « Annuler », and a greyed button for the Account signed in to the
  client. The summary and the deletion run on a low-priority thread; the lists are read when
  « Paramètres » opens and after a deletion, the signed-in state when the section renders.
- KeyForm takes the tracker and emits KeyEvent::AccountDeleted; Page::account_deleted reads the
  Accounts again and shows the active Account when the deleted one was pinned.
- Tests, guide d'utilisation and interface spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:08:27 +01:00

447 lines
16 KiB
Rust

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod banner_art;
mod card;
mod card_grid;
mod card_images;
mod card_lift;
mod card_order;
mod champion_table;
mod local_time;
mod logon;
mod minimized;
mod motion;
mod page;
#[cfg(feature = "profile")]
mod profile;
mod release;
mod ring;
mod settings;
mod single_instance;
mod stage;
mod text;
mod theme;
mod title_bar;
mod tray;
mod worker;
use std::{ops::ControlFlow, sync::Arc};
use arena_tracker_core::{
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::*;
use gpui_kit::*;
use page::{ChampionSortChosen, Launch, LiveMatchStarted, Page, RecapOpened};
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use worker::{CatalogRefresh, 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<Page>,
form: Entity<KeyForm>,
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
catalog_refresh: Option<Arc<CatalogRefresh>>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
/// Started hidden at logon: the first frame, which GPUI draws as the window
/// opens, paints no page, so no portrait is decoded before the window is shown.
blank: bool,
_form_events: Subscription,
_champ_select: Subscription,
_recap: Subscription,
_live_match: Subscription,
_sort: Subscription,
}
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,
} = 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 preferences = store.preferences();
let (tx, rx) = unbounded();
let catalog_refresh = game_data.map(|data| CatalogRefresh::start(data, tx.clone()));
let page = cx.new(|cx| {
Page::new(
tracker.clone(),
Launch {
notice,
following: !first_launch,
champion_sort: preferences.champion_sort,
open_recap_at_match_end: preferences.open_recap_at_match_end,
},
rx,
tx.clone(),
window,
cx,
)
});
let form = cx.new(|cx| KeyForm::new(store, tracker.clone(), first_launch, window, cx));
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, window, 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.catalog_refresh.clone(),
this.tx.clone(),
);
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
// « Paramètres » stays open.
KeyEvent::AccountDeleted(puuid) => {
return this
.page
.update(cx, |page, cx| page.account_deleted(puuid, window, cx));
}
// Only the title bar changes.
KeyEvent::UpdateReady => return cx.notify(),
KeyEvent::Preferences(preferences) => {
let open = preferences.open_recap_at_match_end;
return this
.page
.update(cx, |page, _| page.set_open_recap_at_match_end(open));
}
}
this.show_page(window, cx);
});
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, transition: &page::ChampSelectTransition, window, cx| {
// Only on entry: the window stays open after the champ select.
if transition.entered
&& let Some(hwnd) = tray::window_hwnd(window)
{
// Outside this update: the native calls resize the window through GPUI.
cx.spawn(async move |_, _| tray::reveal(hwnd, true))
.detach();
}
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
this.show_page(window, cx);
}
},
);
// The end of a Match showed its recap: « Paramètres » gives way as for a champ select,
// but the window stays as it is, hidden, minimised or behind League: never in front.
let recap = cx.subscribe_in(&page, window, |this, _, _: &RecapOpened, window, cx| {
if this.screen == Screen::Settings {
this.show_page(window, cx);
}
});
// A Live Match started: « Paramètres » gives way, and a window minimised or hidden in the
// notification area opens again without the focus; unlike a champ select, it is not
// brought above the others, the game's included (#109).
let live_match = cx.subscribe_in(
&page,
window,
|this, _, _: &LiveMatchStarted, window, cx| {
if let Some(hwnd) = tray::window_hwnd(window) {
cx.spawn(async move |_, _| tray::reveal(hwnd, false))
.detach();
}
if this.screen == Screen::Settings {
this.show_page(window, cx);
}
},
);
// Saved with the other preferences; a failure keeps the choice for the session.
let sort = cx.subscribe(
&page,
|this, _, ChampionSortChosen(sort): &ChampionSortChosen, cx| {
this.form
.update(cx, |form, cx| form.save_champion_sort(*sort, cx));
},
);
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(
tracker.clone(),
riot_id.clone(),
catalog_refresh.clone(),
tx.clone(),
);
Screen::Page
};
if hidden {
// Runs once GPUI's first frame is drawn. A hidden or minimized window gets no
// other frame: the page is painted when the window is shown.
cx.defer_in(window, |this, _, cx| {
this.blank = false;
cx.notify();
});
}
RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
catalog_refresh,
fallback_riot_id: riot_id,
tx,
blank: hidden,
_form_events: form_events,
_champ_select: champ_select,
_recap: recap,
_live_match: live_match,
_sort: sort,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
}
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.screen == Screen::Page {
self.screen = Screen::Settings;
// Windows holds the launch at logon: read it as the settings open.
self.form.update(cx, |form, _| {
form.read_logon_launch();
form.read_accounts();
});
self.page.update(cx, |page, cx| page.hidden(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
/// Leaves the key form for the page, discarding half-typed edits.
fn show_page(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.form.update(cx, |form, cx| form.reset(window, cx));
self.screen = Screen::Page;
self.page.update(cx, |page, cx| page.uncovered(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
impl Render for RootView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh =
refresh_button(self.can_refresh(cx), cx).on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.request_refresh(cx));
}
}));
let on_page = self.screen == Screen::Page;
let settings = settings_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)));
// The settings show the ready version next to « Redémarrer ».
let update = self.form.read(cx).update_ready().then(|| {
update_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)))
});
let content = match self.screen {
_ if self.blank => div().into_any_element(),
Screen::Page => self.page.clone().into_any_element(),
Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(),
};
div()
.id("arena-tracker")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(refresh, settings, update, window, cx))
.child(div().flex_1().min_h_0().child(content))
}
}
/// Shown instead of the app when the configuration or the database cannot be loaded.
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
}
impl Render for Unavailable {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(
refresh_button(false, cx),
settings_button(false, cx),
None,
window,
cx,
))
.child(
div()
.v_flex()
.flex_1()
.items_center()
.justify_center()
.children(self.lines.clone()),
)
}
}
fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
// Tab dispatch needs a focused element inside gpui-kit's root key context.
let focus = cx.focus_handle();
focus.focus(window, cx);
focus
}
struct Setup {
tracker: Arc<Tracker>,
/// The cache of the items' and augments' names and icons.
game_data: Option<GameData>,
riot_id: String,
notice: Option<String>,
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<Setup, (Vec<String>, Preferences)> {
let bad_config = |error: String| {
(
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
],
Preferences::default(),
)
};
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()], config.preferences))?
.with_seasons(seasons)
.with_champions(Box::new(DataDragon::new()), dir.join("portraits"))
.with_client(Box::new(LeagueClient::new()));
Ok(Setup {
tracker: Arc::new(tracker),
game_data: Some(GameData::new(dir.join("game-data"))),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
})
}
fn main() {
release::handle_command();
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
};
// Started by the logon entry: hidden, or minimized (#67).
let at_logon = logon::launched_at_logon();
// Only the single instance gets here: a launch relayed to a running one installs nothing.
let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
card_grid::init(cx);
page::init(cx);
theme::init(cx);
#[cfg(feature = "profile")]
profile::start(cx);
let bounds = Bounds::centered(None, size(px(1280.), px(860.)), cx);
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..TitleBar::title_bar_options()
}),
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(MIN_WINDOW_SIZE),
show: !at_logon,
focus: !at_logon,
..Default::default()
};
match startup() {
Ok(mut setup) => {
setup.notice = (update_notice.into_iter().chain(setup.notice))
.reduce(|update, seasons| format!("{update}\n{seasons}"));
gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
motion::follow_windows_setting(window, cx);
minimized::skip_paint_while_minimized(window);
// The settings form installs the tray that hides the window.
let root = cx.new(|cx| RootView::new(setup, at_logon, window, cx));
if at_logon {
tray::start_hidden(window, bounds);
}
root
})
.map(drop)
}
Err((mut lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
lines.extend(update_notice);
single_instance::accept_relaunches(window);
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
apply_theme(preferences.theme, window, cx);
})
.detach();
// Without a readable configuration the one-time notice could not be recorded.
tray::Tray::install_saved(window, preferences.close_to_tray, None, cx);
if at_logon {
tray::start_hidden(window, bounds);
}
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
})
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
#[cfg(test)]
mod tests;