diff --git a/README.md b/README.md index 0337f93..e5c3297 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,8 @@ region = "europe" # facultatif, "europe" par défaut Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement. +L'application y écrit aussi ses préférences (`close_to_tray`, `theme`) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture. + La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée. ## Tests diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 2b87e3e..9a69d2d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -22,7 +22,7 @@ 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, track_maximized}; +use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar}; use worker::{Msg, spawn_follower}; #[derive(Clone, Copy, PartialEq)] @@ -37,7 +37,6 @@ struct RootView { page: Entity, form: Entity, focus: FocusHandle, - maximized: Entity, screen: Screen, tracker: Arc, /// The configured Riot ID, used when the game client is closed on first launch. @@ -97,7 +96,6 @@ impl RootView { page, form, focus: initial_focus(window, cx), - maximized: track_maximized(window, cx), screen, tracker, fallback_riot_id: riot_id, @@ -112,25 +110,23 @@ impl RootView { } impl Render for RootView { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - let refresh = refresh_button() - .disabled(!self.can_refresh(cx)) - .on_click(cx.listener(|this, _, _, cx| { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> 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_manual_refresh(cx)); + this.page.update(cx, |page, cx| page.request_refresh(cx)); } })); - let settings = settings_button() - .disabled(self.screen != Screen::Page) - .on_click(cx.listener(|this, _, window, cx| { + let settings = settings_button(self.screen == Screen::Page, cx).on_click(cx.listener( + |this, _, window, cx| { if this.screen == Screen::Page { this.form.update(cx, |form, cx| form.reset(window, cx)); 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(), @@ -140,7 +136,7 @@ impl Render for RootView { .track_focus(&self.focus) .v_flex() .size_full() - .child(title_bar(refresh, settings, *self.maximized.read(cx), cx)) + .child(title_bar(refresh, settings, window, cx)) .child(div().flex_1().min_h_0().child(content)) } } @@ -149,20 +145,19 @@ impl Render for RootView { struct Unavailable { lines: Vec, focus: FocusHandle, - maximized: Entity, } impl Render for Unavailable { - fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { div() .id("unavailable") .track_focus(&self.focus) .v_flex() .size_full() .child(title_bar( - refresh_button().disabled(true), - settings_button().disabled(true), - *self.maximized.read(cx), + refresh_button(false, cx), + settings_button(false, cx), + window, cx, )) .child( @@ -262,11 +257,11 @@ fn main() { apply_theme(preferences.theme, window, cx); }) .detach(); - tray::Tray::install_saved(window, preferences.close_to_tray, cx); + // 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), - maximized: track_maximized(window, cx), }) }) .map(drop), @@ -283,10 +278,11 @@ mod tests { use arena_tracker_core::{Config, RiotApi, Tracker}; use gpui_kit::{ AppContext as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext, - VisualTestContext, WindowOptions, point, px, + VisualTestContext, WindowOptions, point, }; use super::{KeyStore, RootView, Screen, Setup}; + use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH}; #[gpui::test] fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) { @@ -308,7 +304,8 @@ mod tests { .unwrap() }); let cx = &mut VisualTestContext::from_window(window, cx); - let settings = point(px(54.), px(18.)); + // 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)); diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index 134115d..28dfc65 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -5,6 +5,7 @@ use std::rc::Rc; use std::sync::Arc; use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference}; +use gpui_kit::base::async_util::{Sender, unbounded}; use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::input::{Input, InputEvent, InputState}; use gpui_kit::component::radio::RadioGroup; @@ -64,6 +65,12 @@ impl KeyStore { Ok(()) } + /// A failed write only means the notice is shown again at the next launch. + fn record_tray_notice(&mut self) { + self.config.tray_notice_shown = true; + let _ = self.config.save(&self.path); + } + fn save_preferences(&mut self, preferences: Preferences) -> Result<(), Error> { let previous = std::mem::replace(&mut self.config.preferences, preferences); if let Err(error) = self.config.save(&self.path) { @@ -82,15 +89,15 @@ pub enum KeyEvent { pub struct KeyForm { store: KeyStore, input: Entity, - scroll: ScrollHandle, - key_focus: FocusHandle, - preferences_focus: FocusHandle, /// The first-launch prompt (no key and nothing stored yet) has no way back. first_launch: bool, error: Option, preference_error: Option<&'static str>, tray: Option>, - _subscriptions: [Subscription; 4], + /// The tray reports here that it showed its one-time notice. + notice_shown: Sender<()>, + _subscriptions: [Subscription; 2], + _notice_listener: Task<()>, } impl EventEmitter for KeyForm {} @@ -108,7 +115,19 @@ impl KeyForm { ) -> Self { let preferences = store.config.preferences; apply_theme(preferences.theme, window, cx); - let tray = Tray::install_saved(window, preferences.close_to_tray, cx); + let (notice_shown, notices) = unbounded(); + let notice_listener = cx.spawn(async move |this, cx| { + while notices.recv().await.is_ok() { + if this + .update(cx, |form, _| form.store.record_tray_notice()) + .is_err() + { + return; + } + } + }); + let notice = (!store.config.tray_notice_shown).then(|| notice_shown.clone()); + let tray = Tray::install_saved(window, preferences.close_to_tray, notice, cx); let appearance = cx.observe_window_appearance(window, |this, window, cx| { apply_theme(this.store.config.preferences.theme, window, cx); }); @@ -128,31 +147,16 @@ impl KeyForm { this.save(window, cx); } }); - let key_focus = cx.focus_handle(); - let preferences_focus = cx.focus_handle(); - let reveal_key = cx.on_focus_in(&key_focus, window, |this, window, cx| { - if this.scroll.max_offset().y > px(0.) { - this.scroll.scroll_to_bottom(); - window.defer(cx, |window, _| window.refresh()); - } - }); - let reveal_preferences = cx.on_focus_in(&preferences_focus, window, |this, window, cx| { - if this.scroll.offset().y < px(0.) { - this.scroll.set_offset(point(px(0.), px(0.))); - window.defer(cx, |window, _| window.refresh()); - } - }); KeyForm { first_launch, store, input, - scroll: ScrollHandle::new(), - key_focus, - preferences_focus, error: None, preference_error: None, tray, - _subscriptions: [subscription, appearance, reveal_key, reveal_preferences], + notice_shown, + _subscriptions: [subscription, appearance], + _notice_listener: notice_listener, } } @@ -160,7 +164,6 @@ impl KeyForm { pub fn reset(&mut self, window: &mut Window, cx: &mut Context) { self.error = None; self.preference_error = None; - self.scroll.set_offset(point(px(0.), px(0.))); self.clear(window, cx); cx.notify(); } @@ -176,7 +179,8 @@ impl KeyForm { return; } if preferences.close_to_tray && !previous.close_to_tray { - self.tray = Tray::install(window, cx); + let notice = (!self.store.config.tray_notice_shown).then(|| self.notice_shown.clone()); + self.tray = Tray::install(window, notice, cx); if self.tray.is_none() { self.preference_error = Some(UNAVAILABLE); cx.notify(); @@ -201,8 +205,6 @@ impl KeyForm { let preferences = self.store.config.preferences; let danger = cx.theme().danger; div() - .id("preferences") - .track_focus(&self.preferences_focus) .v_flex() .gap_3() .child( @@ -311,26 +313,26 @@ impl Render for KeyForm { .label("Retour") .on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back))) })); - let fields = div() - .v_flex() - .w(px(520.)) - .max_w_full() - .px_4() - .gap_3() + div() + .size_full() + .flex() + .items_center() + .justify_center() .child( div() - .text_xl() - .font_weight(FontWeight::SEMIBOLD) - .child(title), - ) - .children((!self.first_launch).then(|| self.preferences(cx))) - .child(div().text_color(muted).child(explanation)) - .child( - div() - .id("key-form-controls") - .track_focus(&self.key_focus) .v_flex() + .w(px(520.)) + .max_w_full() + .px_4() .gap_3() + .child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child(title), + ) + .children((!self.first_launch).then(|| self.preferences(cx))) + .child(div().text_color(muted).child(explanation)) .child(Input::new(&self.input).mask_toggle()) .children( self.error @@ -338,20 +340,6 @@ impl Render for KeyForm { .map(|error| div().text_color(danger).child(error)), ) .child(buttons), - ); - div() - .id("key-form") - .size_full() - .overflow_y_scroll() - .track_scroll(&self.scroll) - .child( - div() - .v_flex() - .min_h_full() - .items_center() - .justify_center() - .py_4() - .child(fields), ) } } diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index d7a21fb..ed41a46 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -28,7 +28,6 @@ const NO_MATCH: &str = "Aucune Partie"; /// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves /// each chart 150 px: change them together. const CHARTS_HEIGHT: f32 = 206.; -const NARROW_WIDTH: Pixels = px(540.); /// While an import runs, the page is recomputed at most this often. const RELOAD_EVERY: Duration = Duration::from_secs(1); @@ -87,8 +86,6 @@ pub struct StatsPage { last_active: Option, /// The Account the user picked instead of following the one being updated. pinned: Option, - /// The Account held in view until a manual refresh finishes. - refresh_account: Option, /// The Account of the last requested statistics. shown: Option, progress: Option, @@ -196,7 +193,6 @@ impl StatsPage { .updating .as_ref() .is_some_and(|a| a.puuid == *puuid); - this.refresh_account = None; this.pinned = (!following).then(|| puuid.clone()); this.reload(window, cx); }, @@ -250,7 +246,6 @@ impl StatsPage { accounts: Vec::new(), last_active: None, pinned: None, - refresh_account: None, shown: None, progress: None, refresh: RefreshGate::default(), @@ -288,12 +283,6 @@ impl StatsPage { cx.notify(); } - /// Starts a manual refresh without changing the Account on screen. - pub fn request_manual_refresh(&mut self, cx: &mut Context) { - self.refresh_account = self.viewed().map(|account| account.puuid.clone()); - self.request_refresh(cx); - } - /// Starts a refresh, or queues one behind the refresh already running. pub fn request_refresh(&mut self, cx: &mut Context) { if self.refresh.request() { @@ -311,11 +300,10 @@ impl StatsPage { matches!(self.season, SeasonScope::Season(_)) } - /// The Account shown: held during refresh, pinned, or following updates. + /// The Account shown: the pinned one, else the one being updated. fn viewed(&self) -> Option<&Account> { - self.refresh_account + self.pinned .as_ref() - .or(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()) @@ -372,10 +360,9 @@ impl StatsPage { self.status = status; self.progress = None; self.crashed = false; - // A request made while this one ran (a key saved meanwhile) is served now. - let queued = self.refresh.finished(); self.reload_in_background(window, cx); - if queued { + // 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()); } } @@ -394,19 +381,21 @@ impl StatsPage { self.recompute_in_background(true, window, cx); } } - Msg::Crashed | Msg::RefreshCrashed => { - if matches!(msg, Msg::RefreshCrashed) { - self.refresh.reset(); - self.release_refresh_account(); - } - self.pending_round = false; - self.progress = None; - self.crashed = true; + Msg::Crashed => self.mark_crashed(), + Msg::RefreshCrashed => { + self.refresh.reset(); + self.mark_crashed(); } } cx.notify(); } + fn mark_crashed(&mut self) { + self.pending_round = false; + self.progress = None; + self.crashed = true; + } + /// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a /// visible nor a hidden window waits for them (rule #1). fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context) { @@ -428,9 +417,6 @@ impl StatsPage { if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) { self.pinned = None; } - if !self.refresh.running() { - self.release_refresh_account(); - } let items: Vec = self .accounts .iter() @@ -454,14 +440,6 @@ impl StatsPage { }); } - fn release_refresh_account(&mut self) { - if let Some(puuid) = self.refresh_account.take() - && self.viewed().is_none_or(|account| account.puuid != puuid) - { - self.pinned = Some(puuid); - } - } - /// Settles the scope of the next statistics. Earlier results become stale when they are /// computed again (`computing`) or when the viewed Account changed; a request merely queued /// behind a running job keeps that job's result for the same scope. @@ -626,7 +604,6 @@ fn tile( div() .v_flex() .flex_1() - .min_w(px(120.)) .gap_1() .p_3() .border_1() @@ -658,8 +635,6 @@ fn challenge_tiles( }; div() .h_flex() - .flex_wrap() - .flex_shrink_0() .gap_3() .child(tile( "Champions validés", @@ -713,6 +688,7 @@ fn card( .v_flex() .flex_1() .min_w_0() + .h_full() .gap_2() .p_3() .border_1() @@ -765,7 +741,7 @@ impl ChartsRow { } impl Render for ChartsRow { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { #[cfg(test)] { self.renders += 1; @@ -819,15 +795,7 @@ impl Render for ChartsRow { .into_any_element(), ); } - div() - .h_flex() - .items_stretch() - .when(window.viewport_size().width < NARROW_WIDTH, |row| { - row.flex_col() - }) - .size_full() - .gap_3() - .children(cards) + div().h_flex().size_full().gap_3().children(cards) } } @@ -887,7 +855,7 @@ fn attempts_chart(charts: &Charts) -> Option { } impl Render for StatsPage { - fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let (border, muted) = { let theme = cx.theme(); (theme.border, theme.muted_foreground) @@ -897,93 +865,82 @@ impl Render for StatsPage { let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref()); let busy = self.busy(); let status_line = sync_line(busy, self.progress, self.crashed, self.stored); - let viewport = window.viewport_size(); - let narrow = viewport.width < NARROW_WIDTH; - let charts_height = if narrow && self.in_season() { - px(3. * CHARTS_HEIGHT + 24.) - } else { - px(CHARTS_HEIGHT) - }; div() - .id("statistics") .v_flex() .size_full() - .overflow_y_scroll() .gap_3() .p_3() .when(shown("header"), |page| { page.child( + // The selectors give way first (down to their minimum width), then the status + // wraps onto a second line: nothing is ever clipped. div() .h_flex() - .when(narrow, |header| header.flex_col().items_start()) - .when(!narrow, |header| header.flex_wrap()) - .flex_shrink_0() + .flex_wrap() + .items_center() + .justify_between() .gap_x_3() .gap_y_2() .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.)), + .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( - Select::new(&self.format_select) - .id("format") - .w(px(220.)) - .min_w(px(130.)), - ) - .child( - div() - .ml_auto() - .text_sm() - .whitespace_nowrap() - .text_color(muted) - .child(status_line), + div().h_flex().items_center().gap_3().flex_shrink_0().child( + div() + .text_sm() + .whitespace_nowrap() + .text_color(muted) + .child(status_line), + ), ), ) }) .when(shown("banners"), |page| { - page.child( - div() - .v_flex() - .flex_shrink_0() - .gap_1() - .children(self.banners()), - ) + page.child(div().v_flex().gap_1().children(self.banners())) }) .when(shown("tiles"), |page| { page.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted))) }) .child( - self.charts.clone().cached( - StyleRefinement::default() - .w_full() - .h(charts_height) - .flex_shrink_0(), - ), + self.charts + .clone() + .cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT))), ) .when(shown("tabs"), |page| { page.child( div() .h_flex() - .when(narrow, |filters| filters.flex_col().items_start()) - .when(!narrow, |filters| filters.flex_wrap()) - .flex_shrink_0() .items_center() .justify_between() .gap_3() @@ -1009,14 +966,7 @@ impl Render for StatsPage { ) }) .when(shown("table"), |page| { - page.child( - div() - .flex_1() - .min_h(px(240.)) - // The champion list handles its own wheel events. - .on_scroll(|_, _, cx| cx.stop_propagation()) - .child(self.table.clone()), - ) + page.child(div().flex_1().min_h(px(240.)).child(self.table.clone())) }) } } @@ -1111,8 +1061,9 @@ mod tests { } } - #[gpui::test] - async fn a_manual_refresh_keeps_the_displayed_account_and_format(cx: &mut TestAppContext) { + /// A page on Alice's 3x6 statistics with the Format filter set, whose refresh worker meets Bob + /// (the client adopted another Account) before the UI does. + async fn refresh_towards_bob(cx: &mut TestAppContext, pin_alice: bool) -> Entity { cx.executor().allow_parking(); let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)) .unwrap() @@ -1123,20 +1074,39 @@ mod tests { page.update(cx, |page, cx| { assert_eq!(page.viewed().unwrap().puuid, "Alice"); assert_eq!(page.stats.as_ref().unwrap().formats, [Format::Arena3x6]); + if pin_alice { + page.pinned = Some("Alice".into()); + } page.format = Some(Format::Arena3x6); page.recompute(window, cx); - // The refresh worker sees the newly adopted Account before the UI does. page.tracker.follow_client(0, Some("Bob#EUW"), &mut |_| {}); - page.request_manual_refresh(cx); + page.request_refresh(cx); }); }); cx.condition(&page, |page, _| !page.busy()).await; - page.read_with(cx, |page, cx| { + page + } + + #[gpui::test] + async fn a_refresh_keeps_following_the_account_being_updated(cx: &mut TestAppContext) { + let page = refresh_towards_bob(cx, false).await; + page.read_with(cx, |page, _| { assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob"); - assert_eq!( - page.account_select.read(cx).selected_value().unwrap(), - "Alice" - ); + assert_eq!(page.pinned, None); + assert_eq!(page.viewed().unwrap().puuid, "Bob"); + // Another Account may not have played the Format: the filter is dropped + // (`prepare_statistics`), whatever the refresh. + assert_eq!(page.format, None); + }); + } + + #[gpui::test] + async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) { + let page = refresh_towards_bob(cx, true).await; + page.read_with(cx, |page, _| { + assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob"); + assert_eq!(page.pinned.as_deref(), Some("Alice")); + assert_eq!(page.viewed().unwrap().puuid, "Alice"); assert_eq!(page.format, Some(Format::Arena3x6)); }); } diff --git a/crates/app/src/title_bar.rs b/crates/app/src/title_bar.rs index 692ee15..20c3896 100644 --- a/crates/app/src/title_bar.rs +++ b/crates/app/src/title_bar.rs @@ -1,5 +1,4 @@ use gpui_kit::base::Button as BaseButton; -use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::tooltip::Tooltip; use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _}; use gpui_kit::*; @@ -9,46 +8,67 @@ use windows::Win32::{ UI::WindowsAndMessaging::{PostMessageW, SC_CLOSE, SC_MAXIMIZE, SC_RESTORE, WM_SYSCOMMAND}, }; -const BUTTON_WIDTH: Pixels = px(36.); -const BUTTON_HEIGHT: Pixels = px(28.); -const BAR_HEIGHT: Pixels = px(36.); +// Windows 11 caption metrics. +pub(crate) const BUTTON_WIDTH: Pixels = px(46.); +pub(crate) const BAR_HEIGHT: Pixels = px(32.); -// Leave room for the centered title and both groups in narrow Windows Snap zones. -pub const MIN_WINDOW_SIZE: Size = size(px(330.), px(216.)); +// Six button widths plus room for the centered title, in narrow Windows Snap zones. +pub const MIN_WINDOW_SIZE: Size = size(px(380.), px(216.)); -fn action_button(id: &'static str, icon: IconName, label: &'static str) -> Button { - Button::new(id) - .ghost() - .small() +/// A flat button filling the bar's height, so that when the window is maximized the screen +/// edge (and for Fermer, the top-right corner) still hits it. Only hover and press show. +fn bar_button(id: &'static str, icon: IconName, label: &'static str, cx: &App) -> BaseButton { + BaseButton::new(id) .w(BUTTON_WIDTH) - .h(BUTTON_HEIGHT) - .icon(icon) - .tooltip(label) + .h_full() + .flex_shrink_0() + // Always bordered, so the focus ring does not shift the icon. + .border_1() + .border_color(transparent_black()) + .focus_visible(|style| style.border_color(cx.theme().ring)) + .child(Icon::new(icon).small()) .accessibility_label(label) + .tooltip(move |window, cx| Tooltip::new(label).build(window, cx)) } -pub fn refresh_button() -> Button { - action_button("refresh", IconName::RefreshCw, "Actualiser") -} - -pub fn settings_button() -> Button { - action_button("settings", IconName::Settings, "Paramètres") -} - -pub fn track_maximized(window: &mut Window, cx: &mut App) -> Entity { - cx.new(|cx| { - cx.observe_window_bounds(window, |maximized, window, _| { - // GPUI has already scheduled a redraw for this bounds change. - *maximized = window.is_maximized(); - }) - .detach(); - window.is_maximized() - }) -} - -pub fn title_bar(refresh: Button, settings: Button, maximized: bool, cx: &App) -> impl IntoElement { +fn neutral(button: BaseButton, cx: &App) -> BaseButton { let theme = cx.theme(); - let (icon, label) = if maximized { + button + .hover(|style| style.bg(theme.accent).text_color(theme.accent_foreground)) + .active(|style| style.bg(theme.secondary_active)) +} + +fn action_button( + id: &'static str, + icon: IconName, + label: &'static str, + enabled: bool, + cx: &App, +) -> BaseButton { + let button = bar_button(id, icon, label, cx).disabled(!enabled); + if enabled { + neutral(button, cx) + } else { + button.text_color(cx.theme().muted_foreground) + } +} + +pub fn refresh_button(enabled: bool, cx: &App) -> BaseButton { + action_button("refresh", IconName::RefreshCw, "Actualiser", enabled, cx) +} + +pub fn settings_button(enabled: bool, cx: &App) -> BaseButton { + action_button("settings", IconName::Settings, "Paramètres", enabled, cx) +} + +pub fn title_bar( + refresh: BaseButton, + settings: BaseButton, + window: &Window, + cx: &App, +) -> impl IntoElement { + let theme = cx.theme(); + let (icon, label) = if window.is_maximized() { (IconName::WindowRestore, "Restaurer") } else { (IconName::WindowMaximize, "Agrandir") @@ -68,30 +88,23 @@ pub fn title_bar(refresh: Button, settings: Button, maximized: bool, cx: &App) - .h_flex() .h_full() .flex_1() + .min_w_0() // The third button on the right is balanced by this padding. .pl(BUTTON_WIDTH) .justify_center() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) + .text_xs() .window_control_area(WindowControlArea::Drag) .child(Text::new("window-title".into(), "Arena Tracker".into())), ) .child( - action_button("minimize", IconName::WindowMinimize, "Réduire") - .on_click(|_, window, _| window.minimize_window()), + neutral( + bar_button("minimize", IconName::WindowMinimize, "Réduire", cx), + cx, + ) + .on_click(|_, window, _| window.minimize_window()), ) .child( - BaseButton::new("maximize") - .w(BUTTON_WIDTH) - .h(BUTTON_HEIGHT) - .flex_shrink_0() - .rounded(theme.radius) - .hover(|style| style.bg(theme.accent).text_color(theme.accent_foreground)) - .active(|style| style.bg(theme.secondary_active)) - .focus_visible(|style| style.border_1().border_color(theme.ring)) - .child(Icon::new(icon).small()) - .accessibility_label(label) - .tooltip(move |window, cx| Tooltip::new(label).build(window, cx)) + neutral(bar_button("maximize", icon, label, cx), cx) .window_control_area(WindowControlArea::Max) .on_click(|event, window, _| { // GPUI's native hit target handles mouse clicks and Snap Layouts. @@ -104,9 +117,14 @@ pub fn title_bar(refresh: Button, settings: Button, maximized: bool, cx: &App) - }), ) .child( - action_button("close", IconName::WindowClose, "Fermer") - .danger() - .outline() + // No window_control_area: the click stays in Rust and SC_CLOSE keeps Alt+F4 + // semantics. Enter, Space and the accessibility Click (a synthesized mouse + // click) all reach on_click. + bar_button("close", IconName::WindowClose, "Fermer", cx) + // Windows' own close colours: the theme's danger pair is meant for text and + // gives a red-on-red icon in the dark theme. + .hover(|style| style.bg(rgb(0xC42B1C)).text_color(white())) + .active(|style| style.bg(rgba(0xC42B1CE6)).text_color(white())) .on_click(|_, window, _| window_command(window, SC_CLOSE)), ) } diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs index 814b83c..401746b 100644 --- a/crates/app/src/tray.rs +++ b/crates/app/src/tray.rs @@ -5,6 +5,7 @@ use std::{ rc::{Rc, Weak}, }; +use gpui_kit::base::async_util::Sender; use gpui_kit::{App, PromptLevel, Subscription, Window}; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use windows::Win32::{ @@ -12,10 +13,10 @@ use windows::Win32::{ System::LibraryLoader::GetModuleHandleW, UI::{ Shell::{ - DefSubclassProc, NIF_ICON, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIM_ADD, NIM_DELETE, - NIM_SETFOCUS, NIM_SETVERSION, NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW, - NOTIFYICONIDENTIFIER, RemoveWindowSubclass, SetWindowSubclass, Shell_NotifyIconGetRect, - Shell_NotifyIconW, + DefSubclassProc, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIIF_INFO, + NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETFOCUS, NIM_SETVERSION, NIN_SELECT, + NOTIFYICON_VERSION_4, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER, RemoveWindowSubclass, + SetWindowSubclass, Shell_NotifyIconGetRect, Shell_NotifyIconW, }, WindowsAndMessaging::*, }, @@ -29,21 +30,31 @@ const QUIT: u32 = 2; const NIN_KEYSELECT: u32 = NIN_SELECT | 1; pub const UNAVAILABLE: &str = "La zone de notification est indisponible. La fenêtre reste accessible."; +const NOTICE_TITLE: &str = "Arena Tracker reste ouvert"; +const NOTICE_TEXT: &str = "L’application continue dans la zone de notification. Cliquez sur \ + son icône pour la rouvrir, ou faites un clic droit pour la quitter."; pub struct Tray { hwnd: HWND, taskbar_created: u32, enabled: Cell, hidden: Cell, + /// Until the one-time notice is shown: told when it is, so that it can be recorded. + notice: Cell>>, _quit: Subscription, } impl Tray { - pub fn install_saved(window: &mut Window, enabled: bool, cx: &mut App) -> Option> { + pub fn install_saved( + window: &mut Window, + enabled: bool, + notice: Option>, + cx: &mut App, + ) -> Option> { if !enabled { return None; } - let tray = Self::install(window, cx); + let tray = Self::install(window, notice, cx); if tray.is_none() { window.defer(cx, |window, cx| { drop(window.prompt(PromptLevel::Warning, UNAVAILABLE, None, &["OK"], cx)); @@ -52,7 +63,7 @@ impl Tray { tray } - pub fn install(window: &Window, cx: &App) -> Option> { + pub fn install(window: &Window, notice: Option>, cx: &App) -> Option> { let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw() else { return None; @@ -75,6 +86,7 @@ impl Tray { taskbar_created, enabled: Cell::new(true), hidden: Cell::new(false), + notice: Cell::new(notice), _quit: quit, } }); @@ -118,11 +130,7 @@ impl Tray { hIcon: icon, ..self.icon_data() }; - let mut tip = [0; 128]; - for (unit, letter) in tip.iter_mut().zip("Arena Tracker".encode_utf16()) { - *unit = letter; - } - data.szTip = tip; + fill(&mut data.szTip, "Arena Tracker"); if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() { return false; } @@ -135,6 +143,26 @@ impl Tray { } } + /// Says once, as a Windows notification, that closing kept the app running here. + fn show_notice(&self) { + let Some(shown) = self.notice.take() else { + return; + }; + let mut data = NOTIFYICONDATAW { + uFlags: NIF_INFO, + dwInfoFlags: NIIF_INFO, + ..self.icon_data() + }; + fill(&mut data.szInfoTitle, NOTICE_TITLE); + fill(&mut data.szInfo, NOTICE_TEXT); + if unsafe { Shell_NotifyIconW(NIM_MODIFY, &data) }.as_bool() { + // Recorded by the settings form, outside this window procedure. + let _ = shown.try_send(()); + } else { + self.notice.set(Some(shown)); + } + } + fn remove_icon(&self) { if self.hidden.replace(false) { let _ = unsafe { Shell_NotifyIconW(NIM_DELETE, &self.icon_data()) }; @@ -220,6 +248,14 @@ impl Tray { } } +/// Copies `text` into a fixed Win32 string field, truncated, always ending with a NUL. +fn fill(field: &mut [u16], text: &str) { + let room = field.len() - 1; + for (unit, letter) in field[..room].iter_mut().zip(text.encode_utf16()) { + *unit = letter; + } +} + unsafe extern "system" fn window_proc( hwnd: HWND, message: u32, @@ -250,6 +286,7 @@ unsafe extern "system" fn window_proc( if tray.add_icon() { tray.hidden.set(true); let _ = unsafe { ShowWindow(hwnd, SW_HIDE) }; + tray.show_notice(); } else { tray.report_unavailable(); } diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs index 2a3ab48..259aac1 100644 --- a/crates/core/src/config.rs +++ b/crates/core/src/config.rs @@ -13,19 +13,31 @@ pub struct Config { pub riot_id: String, #[serde(default = "default_region")] pub region: String, + /// Whether the one-time notice about closing to the notification area was shown. + #[serde(default)] + pub tray_notice_shown: bool, #[serde(flatten)] pub preferences: Preferences, #[serde(flatten)] other: toml::Table, } -#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(default)] pub struct Preferences { pub close_to_tray: bool, pub theme: ThemePreference, } +impl Default for Preferences { + fn default() -> Self { + Self { + close_to_tray: true, + theme: ThemePreference::System, + } + } +} + #[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum ThemePreference { @@ -57,6 +69,7 @@ impl Config { riot_api_key: String::new(), riot_id: String::new(), region: default_region(), + tray_notice_shown: false, preferences: Preferences::default(), other: toml::Table::new(), }) @@ -98,7 +111,8 @@ mod tests { let config = load("riot_api_key = \"k\"\nriot_id = \"Joueur#EUW\"\n").unwrap(); assert_eq!(config.riot_id, "Joueur#EUW"); assert_eq!(config.region, "europe"); - assert!(!config.preferences.close_to_tray); + assert!(!config.tray_notice_shown); + assert!(config.preferences.close_to_tray); assert_eq!(config.preferences.theme, ThemePreference::System); } @@ -136,7 +150,7 @@ mod tests { ("", "", "europe") ); assert!(!dir.path().join("config.toml").exists()); - assert!(!config.preferences.close_to_tray); + assert!(config.preferences.close_to_tray); assert_eq!(config.preferences.theme, ThemePreference::System); } @@ -150,14 +164,16 @@ mod tests { ) .unwrap(); let mut config = Config::load(&path).unwrap(); + config.tray_notice_shown = true; config.preferences = Preferences { - close_to_tray: true, + close_to_tray: false, theme: ThemePreference::Dark, }; config.save(&path).unwrap(); let loaded = Config::load_or_default(&path).unwrap(); assert_eq!(loaded.preferences, config.preferences); + assert!(loaded.tray_notice_shown); assert_eq!(loaded.other["other"]["value"].as_integer(), Some(42)); assert_eq!(loaded.riot_api_key, "RGAPI-secret"); assert_eq!( @@ -175,6 +191,7 @@ mod tests { riot_api_key: "RGAPI-secret".into(), riot_id: String::new(), region: "europe".into(), + tray_notice_shown: false, preferences: Preferences::default(), other: toml::Table::new(), };