The sheet covers the card with the Season's Matches, Wins, best Placement and Attempts, and the date of the first top 1 for a Completed champion. Its lines are prepared in Card::from_row; only the shown cards build it. The grid keeps the hovered card and one focus handle per card id, and handles Tab and Shift-Tab itself, scrolling the next card's row into view. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
473 lines
18 KiB
Rust
473 lines
18 KiB
Rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
|
|
mod card;
|
|
mod card_grid;
|
|
mod champion_table;
|
|
mod page;
|
|
#[cfg(feature = "profile")]
|
|
mod profile;
|
|
mod release;
|
|
mod settings;
|
|
mod single_instance;
|
|
mod text;
|
|
mod title_bar;
|
|
mod tray;
|
|
mod worker;
|
|
|
|
use std::{borrow::Cow, ops::ControlFlow, 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 page::Page;
|
|
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
|
|
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
|
|
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<Page>,
|
|
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| {
|
|
Page::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 => {}
|
|
// Only the title bar changes.
|
|
KeyEvent::UpdateReady => return cx.notify(),
|
|
}
|
|
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)).detach();
|
|
}
|
|
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()
|
|
}
|
|
|
|
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
|
if self.screen == Screen::Page {
|
|
self.screen = Screen::Settings;
|
|
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.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 {
|
|
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>,
|
|
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() {
|
|
release::handle_command();
|
|
let Some(single_instance::Primary {
|
|
instance: _instance,
|
|
starting,
|
|
}) = single_instance::launch()
|
|
else {
|
|
return;
|
|
};
|
|
// Only the single instance gets here: a launch relayed to a running one installs nothing.
|
|
let ControlFlow::Continue(update_notice) = release::update_at_launch() 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);
|
|
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(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);
|
|
cx.new(|cx| RootView::new(setup, window, cx))
|
|
})
|
|
.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);
|
|
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, UpdateChannel};
|
|
use gpui_kit::component::{Theme, ThemeMode};
|
|
use gpui_kit::{
|
|
AppContext as _, Entity, 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};
|
|
use crate::worker::UpdateChecked;
|
|
|
|
// 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:?}");
|
|
});
|
|
}
|
|
|
|
/// A first launch: no key and nothing stored.
|
|
fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>) {
|
|
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()
|
|
});
|
|
(VisualTestContext::from_window(window, cx), root)
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestAppContext) {
|
|
let (mut cx, root) = first_launch(cx);
|
|
let cx = &mut cx;
|
|
root.update(cx, |root, cx| {
|
|
root.screen = Screen::Page;
|
|
cx.notify();
|
|
});
|
|
// Centre of the third action button, title-bar drag area until an update is ready.
|
|
let update = point(BUTTON_WIDTH * 2.5, BAR_HEIGHT / 2.);
|
|
cx.update(|window, cx| window.draw(cx).clear(cx));
|
|
cx.simulate_click(update, Modifiers::none());
|
|
assert!(root.read_with(cx, |root, _| root.screen == Screen::Page));
|
|
|
|
let form = root.read_with(cx, |root, _| root.form.clone());
|
|
form.update(cx, |form, cx| {
|
|
let checked = UpdateChecked {
|
|
channel: UpdateChannel::Stable,
|
|
ready: Some("1.0.1".into()),
|
|
};
|
|
form.update_checked(checked, cx);
|
|
});
|
|
cx.update(|window, cx| window.draw(cx).clear(cx));
|
|
cx.simulate_click(update, Modifiers::none());
|
|
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
|
|
}
|
|
|
|
#[gpui::test]
|
|
fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) {
|
|
let (mut cx, root) = first_launch(cx);
|
|
let cx = &mut 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));
|
|
}
|
|
}
|