Files
arena-tracker/crates/app/src/main.rs
T
nessarandClaude Opus 5.5 6d07a9641f
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 39s
Address single-instance review findings (#50)
- Reopen the window even when the relaunch's ack event is gone.
- Exit quietly instead of panicking on timeout or Win32 error; bound the startup gate wait.
- Fail softly in accept_relaunches; name the locks (Primary, HeldMutex).
- Share window_hwnd, derive REOPEN from TRAY_MESSAGE, name the marker.
- Test a crashed primary and a relaunch that finds no window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:09:47 +01:00

408 lines
15 KiB
Rust

#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod champion_table;
#[cfg(feature = "profile")]
mod profile;
mod settings;
mod single_instance;
mod stats_page;
mod text;
mod title_bar;
mod tray;
mod worker;
use std::{borrow::Cow, rc::Rc, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, 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 settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use stats_page::StatsPage;
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar};
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<StatsPage>,
form: Entity<KeyForm>,
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
_form_events: Subscription,
_champ_select: Subscription,
}
impl RootView {
fn new(setup: Setup, window: &mut Window, cx: &mut Context<Self>) -> 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) = unbounded();
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 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.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 => {}
}
this.show_page(window, cx);
});
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, _: &stats_page::ChampSelectTransition, window, cx| {
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
this.show_page(window, cx);
}
},
);
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
Screen::Page
};
RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_form_events: form_events,
_champ_select: champ_select,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
}
/// 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.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 settings = settings_button(self.screen == Screen::Page, cx).on_click(cx.listener(
|this, _, window, cx| {
if this.screen == Screen::Page {
this.screen = Screen::Settings;
this.focus.focus(window, cx);
cx.notify();
}
},
));
let content = match self.screen {
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, 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),
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>,
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),
riot_id: config.riot_id.clone(),
notice,
store: KeyStore::new(path, config, api),
})
}
/// DirectWrite exposes the variable font's text optical size as its own family.
const INTER: &str = "Inter Variable Text";
/// Sets Inter as the interface font and adjusts the theme colours. Needs `gpui_kit::init` first.
fn init_theme(cx: &mut App) {
let text = cx.text_system();
let ttf = include_bytes!("../assets/InterVariable.ttf");
if let Err(error) = text.add_fonts(vec![Cow::Borrowed(ttf)]) {
eprintln!("Failed to load Inter: {error}");
}
// A family that falls back costs a font lookup on every text run: keep the system font then.
let inter = font(INTER);
if text.get_font_for_id(text.resolve_font(&inter)) == Some(inter) {
Theme::update(cx, |theme| theme.font_family = INTER.into());
}
// The default dark table header text has low contrast against its background.
let dark = Rc::make_mut(&mut Theme::global_mut(cx).dark_theme);
dark.colors.table_head_foreground = dark.colors.muted_foreground.clone();
}
fn main() {
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
init_theme(cx);
#[cfg(feature = "profile")]
profile::start(cx);
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..TitleBar::title_bar_options()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
window_min_size: Some(MIN_WINDOW_SIZE),
..Default::default()
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err((lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
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);
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
})
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{Config, RiotApi, Tracker};
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{
AppContext as _, FontWeight, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,
TestAppContext, VisualTestContext, WindowOptions, font, point, px,
};
use super::{INTER, KeyStore, RootView, Screen, Setup};
use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH};
// Not #[gpui::test]: its text system is a no-op, and this checks DirectWrite's real one.
#[test]
fn inter_is_used_in_both_themes() {
let platform = gpui_kit::platform::current_platform(false);
let cx = TestAppContext::build_with_text_system(
gpui::TestDispatcher::new(0),
None,
platform.text_system(),
);
cx.update(|cx| {
gpui_kit::init(cx);
super::init_theme(cx);
for mode in [ThemeMode::Light, ThemeMode::Dark] {
Theme::change(mode, None, cx);
assert_eq!(Theme::global(cx).font_family.as_str(), INTER);
}
// DirectWrite returns the nearest weight, so only a wider glyph proves a semibold face.
let text = cx.text_system();
let [regular, semibold] = [FontWeight::NORMAL, FontWeight::SEMIBOLD].map(|weight| {
let mut requested = font(INTER);
requested.weight = weight;
let id = text.resolve_font(&requested);
assert_eq!(text.get_font_for_id(id), Some(requested));
text.advance(id, px(14.), 'm').unwrap().width
});
assert!(semibold > regular, "{semibold:?} <= {regular:?}");
});
}
#[gpui::test]
fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = Config::load_or_default(Path::new(":memory:")).unwrap();
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(),
),
riot_id: String::new(),
notice: None,
store: KeyStore::new("unused.toml".into(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
// Centre of the second action button.
let settings = point(BUTTON_WIDTH * 1.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(settings, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Prompt));
// Model a keyless launch with stored data, where Settings is available.
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
assert!(!root.read_with(cx, |root, cx| root.can_refresh(cx)));
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_keystrokes("tab");
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
}