Add a custom Windows title bar (#24)
CI / core (pull_request) Successful in 1m17s

This commit is contained in:
nessar committed 2026-11-18 21:11:21 +01:00
1 parent a2d58c000c
commit 23eb933a68
5 files changed
+268 -70

No files matched your search

+138 -24
View File
@@ -6,6 +6,7 @@ mod profile;
mod settings;
mod stats_page;
mod text;
mod title_bar;
mod tray;
mod worker;
@@ -20,7 +21,8 @@ use gpui_kit::component::*;
use gpui_kit::*;
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use stats_page::{PageEvent, StatsPage};
use stats_page::StatsPage;
use title_bar::{action_button, title_bar};
use worker::{Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
@@ -34,12 +36,13 @@ enum Screen {
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>,
_subscriptions: Vec<Subscription>,
_subscriptions: [Subscription; 2],
}
impl RootView {
@@ -66,19 +69,16 @@ impl RootView {
)
});
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| {
let mut busy = page.read(cx).busy();
let subscriptions = [
cx.observe(&page, move |_, page, cx| {
let next = page.read(cx).busy();
if next != busy {
busy = next;
cx.notify();
}
}),
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.
@@ -91,6 +91,7 @@ impl RootView {
KeyEvent::Back => {}
}
this.screen = Screen::Page;
this.focus.focus(window, cx);
cx.notify();
}),
];
@@ -103,6 +104,7 @@ impl RootView {
RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
fallback_riot_id: riot_id,
@@ -110,32 +112,82 @@ impl RootView {
_subscriptions: subscriptions,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
}
}
impl Render for RootView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh = action_button("refresh", IconName::RefreshCw, "Actualiser")
.disabled(!self.can_refresh(cx))
.on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.begin_refresh(cx));
}
}));
let settings = action_button("settings", IconName::Settings, "Paramètres")
.disabled(self.screen != Screen::Page)
.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(),
};
div().size_full().child(content)
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(Vec<String>);
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
}
impl Render for Unavailable {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.items_center()
.justify_center()
.children(self.0.clone())
.child(title_bar(
action_button("refresh", IconName::RefreshCw, "Actualiser").disabled(true),
action_button("settings", IconName::Settings, "Paramètres").disabled(true),
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,
@@ -193,13 +245,14 @@ fn main() {
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..Default::default()
..TitleBar::title_bar_options()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
window_min_size: Some(size(px(540.), px(360.))),
..Default::default()
};
match startup() {
@@ -215,10 +268,71 @@ fn main() {
})
.detach();
tray::Tray::install_saved(window, preferences.close_to_tray, cx);
cx.new(|_| Unavailable(lines))
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
})
.map(drop),
}
.expect("Failed to open window");
});
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{Config, RiotApi, Tracker};
use gpui_kit::{
AppContext as _, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
VisualTestContext, WindowOptions, point, px,
};
use super::{KeyStore, RootView, Screen, Setup};
#[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);
let settings = point(px(54.), px(18.));
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));
}
}
+4
View File
@@ -93,6 +93,10 @@ pub struct KeyForm {
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn has_key(&self) -> bool {
self.store.has_key()
}
pub fn new(
store: KeyStore,
first_launch: bool,
+7 -33
View File
@@ -10,12 +10,11 @@ use arena_tracker_core::{
use gpui_kit::base::async_util::{Receiver, Sender};
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::input::{Input, InputEvent, InputState};
use gpui_kit::component::select::{Select, SelectEvent, SelectItem, SelectState};
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, Disableable as _, IndexPath, Sizable as _};
use gpui_kit::component::{ActiveTheme as _, IndexPath, Sizable as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
@@ -58,10 +57,6 @@ pub fn shown(part: &str) -> bool {
}
}
pub enum PageEvent {
OpenSettings,
}
/// One Account in the selector; its value is the puuid.
#[derive(Clone, PartialEq)]
struct AccountItem {
@@ -122,8 +117,6 @@ pub struct StatsPage {
_listener: Task<()>,
}
impl EventEmitter<PageEvent> 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] = [
@@ -298,7 +291,7 @@ impl StatsPage {
cx.notify();
}
fn busy(&self) -> bool {
pub fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
@@ -875,8 +868,7 @@ impl Render for StatsPage {
.p_3()
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the buttons
// wrap onto a second line: nothing is ever clipped.
// The status wraps below the selectors on a narrow window.
div()
.h_flex()
.flex_wrap()
@@ -919,28 +911,10 @@ impl Render for StatsPage {
)
.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)),
)),
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
),
)
})
+115
View File
@@ -0,0 +1,115 @@
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::*;
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use windows::Win32::{
Foundation::{HWND, LPARAM, WPARAM},
UI::WindowsAndMessaging::{PostMessageW, SC_CLOSE, SC_MAXIMIZE, SC_RESTORE, WM_SYSCOMMAND},
};
const BUTTON_WIDTH: Pixels = px(36.);
const BUTTON_HEIGHT: Pixels = px(28.);
pub fn action_button(id: &'static str, icon: IconName, label: &'static str) -> Button {
Button::new(id)
.ghost()
.small()
.w(BUTTON_WIDTH)
.h(BUTTON_HEIGHT)
.icon(icon)
.tooltip(label)
.accessibility_label(label)
}
pub fn title_bar(refresh: Button, settings: Button, window: &Window, cx: &App) -> impl IntoElement {
let theme = cx.theme();
let (icon, label) = if window.is_maximized() {
(IconName::WindowRestore, "Restaurer")
} else {
(IconName::WindowMaximize, "Agrandir")
};
div()
.h_flex()
.w_full()
.h(px(36.))
.flex_shrink_0()
.bg(theme.title_bar)
.border_b_1()
.border_color(theme.title_bar_border)
.child(refresh)
.child(settings)
.child(
div()
.h_flex()
.h_full()
.flex_1()
// The third button on the right is balanced by this padding.
.pl(BUTTON_WIDTH)
.justify_center()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
.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()),
)
.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))
.window_control_area(WindowControlArea::Max)
.on_click(|event, window, _| {
// GPUI's native hit target handles mouse clicks and Snap Layouts.
if !matches!(event, ClickEvent::Mouse(_)) {
toggle_maximize(window);
}
})
.on_a11y_action(AccessibleAction::Click, |_, window, _| {
toggle_maximize(window);
}),
)
.child(
action_button("close", IconName::WindowClose, "Fermer")
.danger()
.outline()
.on_click(|_, window, _| window_command(window, SC_CLOSE)),
)
}
fn toggle_maximize(window: &Window) {
let command = if window.is_maximized() {
SC_RESTORE
} else {
SC_MAXIMIZE
};
window_command(window, command);
}
fn window_command(window: &Window, command: u32) {
if let Ok(handle) = HasWindowHandle::window_handle(window)
&& let RawWindowHandle::Win32(handle) = handle.as_raw()
{
let hwnd = HWND(handle.hwnd.get() as _);
// Post so the native command runs after GPUI finishes dispatching this click.
let _ = unsafe {
PostMessageW(
Some(hwnd),
WM_SYSCOMMAND,
WPARAM(command as usize),
LPARAM(0),
)
};
}
}