Add tray and theme settings (#21)
CI / core (pull_request) Successful in 1m13s
CI / core (push) Successful in 44s

This commit was merged in pull request #43.
This commit is contained in:
nessar committed 2026-11-18 00:36:15 +01:00
1 parent 28319fc133
commit d7bd69c35d
7 files changed
+520 -37

No files matched your search

+8
View File
@@ -11,6 +11,14 @@ profile = ["gpui-kit/profiler"]
arena-tracker-core = { path = "../core" }
gpui-kit = "=0.9.1"
[target.'cfg(windows)'.dependencies]
raw-window-handle = "0.6"
windows = { version = "0.62", features = [
"Win32_System_LibraryLoader",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
# The GPUI that gpui-kit pins (upgrade them together), for its test context. Not gpui-kit's own
# test-support: its gpui-fast features would force older wgpu and others into Cargo.lock.
+21 -23
View File
@@ -6,18 +6,20 @@ mod profile;
mod settings;
mod stats_page;
mod text;
mod tray;
mod worker;
use std::{rc::Rc, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, RiotApi, Tracker, data_dir, default_seasons, load_seasons,
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};
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use stats_page::{PageEvent, StatsPage};
use worker::{Msg, spawn_follower};
@@ -143,12 +145,15 @@ struct Setup {
/// 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>> {
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(),
]
(
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()))?;
@@ -164,7 +169,7 @@ fn startup() -> Result<Setup, Vec<String>> {
};
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()])?
.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()));
@@ -176,18 +181,6 @@ fn startup() -> Result<Setup, Vec<String>> {
})
}
fn follow_system_appearance(window: &mut Window, cx: &mut App) {
let sync = |window: &mut Window, cx: &mut App| {
let mode = ThemeMode::from(window.appearance());
if cx.theme().mode != mode {
Theme::sync_system_appearance(Some(window), cx);
debug_assert_eq!(cx.theme().mode, mode);
}
};
sync(window, cx);
window.observe_window_appearance(sync).detach();
}
fn main() {
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
@@ -211,12 +204,17 @@ fn main() {
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err(lines) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
Err((lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
apply_theme(preferences.theme, window, cx);
})
.detach();
tray::Tray::install_saved(window, preferences.close_to_tray, cx);
cx.new(|_| Unavailable(lines))
})
.map(drop),
+153 -7
View File
@@ -1,18 +1,43 @@
//! The Riot API key form: the first-launch prompt and the settings view.
//! The first-launch Riot API key prompt and the settings view.
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, RiotApi};
use arena_tracker_core::{Config, Error, Preferences, RiotApi, ThemePreference};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme, ThemeMode};
use gpui_kit::*;
use crate::tray::{Tray, UNAVAILABLE};
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
const THEMES: [(ThemePreference, &str); 3] = [
(ThemePreference::System, "Système"),
(ThemePreference::Light, "Clair"),
(ThemePreference::Dark, "Sombre"),
];
/// Where the key lives: the config file, and the running Riot client that uses it.
fn theme_mode(preference: ThemePreference, system: ThemeMode) -> ThemeMode {
match preference {
ThemePreference::System => system,
ThemePreference::Light => ThemeMode::Light,
ThemePreference::Dark => ThemeMode::Dark,
}
}
pub fn apply_theme(preference: ThemePreference, window: &mut Window, cx: &mut App) {
let mode = theme_mode(preference, ThemeMode::from(window.appearance()));
if cx.theme().mode != mode {
Theme::change(mode, Some(window), cx);
}
}
/// The local config file and the running Riot client that uses its key.
pub struct KeyStore {
path: PathBuf,
config: Config,
@@ -38,6 +63,15 @@ impl KeyStore {
self.api.set_key(key.to_string());
Ok(())
}
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) {
self.config.preferences = previous;
return Err(error);
}
Ok(())
}
}
pub enum KeyEvent {
@@ -51,7 +85,9 @@ pub struct KeyForm {
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
_subscription: Subscription,
preference_error: Option<&'static str>,
tray: Option<Rc<Tray>>,
_subscriptions: [Subscription; 2],
}
impl EventEmitter<KeyEvent> for KeyForm {}
@@ -63,6 +99,12 @@ impl KeyForm {
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let preferences = store.config.preferences;
apply_theme(preferences.theme, window, cx);
let tray = Tray::install_saved(window, preferences.close_to_tray, cx);
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
apply_theme(this.store.config.preferences.theme, window, cx);
});
let placeholder = if store.has_key() {
PLACEHOLDER_SAVED
} else {
@@ -84,17 +126,100 @@ impl KeyForm {
store,
input,
error: None,
_subscription: subscription,
preference_error: None,
tray,
_subscriptions: [subscription, appearance],
}
}
/// Back to an empty field, as when the form is opened again.
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
self.preference_error = None;
self.clear(window, cx);
cx.notify();
}
fn set_preferences(
&mut self,
preferences: Preferences,
window: &mut Window,
cx: &mut Context<Self>,
) {
let previous = self.store.config.preferences;
if previous == preferences {
return;
}
if preferences.close_to_tray && !previous.close_to_tray {
self.tray = Tray::install(window, cx);
if self.tray.is_none() {
self.preference_error = Some(UNAVAILABLE);
cx.notify();
return;
}
}
self.preference_error = if self.store.save_preferences(preferences).is_err() {
Some("Impossible d’enregistrer les préférences.")
} else {
apply_theme(preferences.theme, window, cx);
None
};
if !self.store.config.preferences.close_to_tray
&& let Some(tray) = self.tray.take()
{
tray.uninstall();
}
cx.notify();
}
fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.config.preferences;
let danger = cx.theme().danger;
div()
.v_flex()
.gap_3()
.child(
Switch::new("close-to-tray")
.label("Fermer dans la zone de notification")
.checked(preferences.close_to_tray)
.on_change(cx.listener(|this, enabled, window, cx| {
this.set_preferences(
Preferences {
close_to_tray: *enabled,
..this.store.config.preferences
},
window,
cx,
);
})),
)
.child(
div().v_flex().gap_1().child("Thème").child(
RadioGroup::horizontal("theme")
.children(THEMES.map(|(_, label)| label))
.selected_index(
THEMES
.iter()
.position(|(theme, _)| *theme == preferences.theme),
)
.on_change(cx.listener(|this, index: &usize, window, cx| {
this.set_preferences(
Preferences {
theme: THEMES[*index].0,
..this.store.config.preferences
},
window,
cx,
);
})),
),
)
.children(
self.preference_error
.map(|error| div().text_color(danger).child(error)),
)
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
@@ -147,7 +272,11 @@ impl Render for KeyForm {
.child(
Button::new("save")
.primary()
.label("Enregistrer")
.label(if self.first_launch {
"Enregistrer"
} else {
"Enregistrer la clé"
})
.on_click(cx.listener(|this, _, window, cx| this.save(window, cx))),
)
.children((!self.first_launch).then(|| {
@@ -164,6 +293,8 @@ impl Render for KeyForm {
div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
@@ -171,6 +302,7 @@ impl Render for KeyForm {
.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(
@@ -182,3 +314,17 @@ impl Render for KeyForm {
)
}
}
#[cfg(test)]
mod tests {
use super::{ThemeMode, ThemePreference, theme_mode};
#[test]
fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
for system in [ThemeMode::Light, ThemeMode::Dark] {
assert_eq!(theme_mode(ThemePreference::System, system), system);
assert_eq!(theme_mode(ThemePreference::Light, system), ThemeMode::Light);
assert_eq!(theme_mode(ThemePreference::Dark, system), ThemeMode::Dark);
}
}
}
+286
View File
@@ -0,0 +1,286 @@
//! Keeps the existing GPUI window alive while it is hidden in the Windows notification area.
use std::{
cell::Cell,
rc::{Rc, Weak},
};
use gpui_kit::{App, PromptLevel, Subscription, Window};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use windows::Win32::{
Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, WPARAM},
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,
},
WindowsAndMessaging::*,
},
};
use windows::core::{PCWSTR, w};
const TRAY_MESSAGE: u32 = WM_APP + 1;
const ICON_ID: u32 = 1;
const OPEN: u32 = 1;
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.";
pub struct Tray {
hwnd: HWND,
taskbar_created: u32,
enabled: Cell<bool>,
hidden: Cell<bool>,
_quit: Subscription,
}
impl Tray {
pub fn install_saved(window: &mut Window, enabled: bool, cx: &mut App) -> Option<Rc<Self>> {
if !enabled {
return None;
}
let tray = Self::install(window, cx);
if tray.is_none() {
window.defer(cx, |window, cx| {
drop(window.prompt(PromptLevel::Warning, UNAVAILABLE, None, &["OK"], cx));
});
}
tray
}
pub fn install(window: &Window, cx: &App) -> Option<Rc<Self>> {
let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw()
else {
return None;
};
let hwnd = HWND(handle.hwnd.get() as _);
let taskbar_created = unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) };
if taskbar_created == 0 {
return None;
}
let tray = Rc::new_cyclic(|weak: &Weak<Self>| {
let weak = weak.clone();
let quit = cx.on_app_quit(move |_| {
if let Some(tray) = weak.upgrade() {
tray.remove_icon();
}
async {}
});
Self {
hwnd,
taskbar_created,
enabled: Cell::new(true),
hidden: Cell::new(false),
_quit: quit,
}
});
// The subclass owns one reference until WM_NCDESTROY. This window belongs to the UI thread.
let data = Rc::into_raw(tray.clone());
if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), data as usize, data as usize) }
.as_bool()
{
drop(unsafe { Rc::from_raw(data) });
return None;
}
Some(tray)
}
pub fn uninstall(self: Rc<Self>) {
self.enabled.set(false);
let data = Rc::as_ptr(&self);
if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), data as usize) }.as_bool() {
drop(unsafe { Rc::from_raw(data) });
}
}
fn icon_data(&self) -> NOTIFYICONDATAW {
NOTIFYICONDATAW {
cbSize: size_of::<NOTIFYICONDATAW>() as u32,
hWnd: self.hwnd,
uID: ICON_ID,
..Default::default()
}
}
fn add_icon(&self) -> bool {
unsafe {
let icon = GetModuleHandleW(None)
.and_then(|module| LoadIconW(Some(HINSTANCE(module.0)), PCWSTR(1 as _)))
.or_else(|_| LoadIconW(None, IDI_APPLICATION));
let Ok(icon) = icon else { return false };
let mut data = NOTIFYICONDATAW {
uFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP,
uCallbackMessage: TRAY_MESSAGE,
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;
if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
return false;
}
data.Anonymous.uVersion = NOTIFYICON_VERSION_4;
if !Shell_NotifyIconW(NIM_SETVERSION, &data).as_bool() {
let _ = Shell_NotifyIconW(NIM_DELETE, &data);
return false;
}
true
}
}
fn remove_icon(&self) {
if self.hidden.replace(false) {
let _ = unsafe { Shell_NotifyIconW(NIM_DELETE, &self.icon_data()) };
}
}
fn open(&self) {
self.remove_icon();
unsafe {
let command = if IsIconic(self.hwnd).as_bool() {
SW_RESTORE
} else {
SW_SHOW
};
let _ = ShowWindow(self.hwnd, command);
let _ = SetForegroundWindow(self.hwnd);
}
}
fn report_unavailable(&self) {
let message: Vec<_> = UNAVAILABLE.encode_utf16().chain([0]).collect();
unsafe {
MessageBoxW(
Some(self.hwnd),
PCWSTR(message.as_ptr()),
w!("Arena Tracker"),
MB_OK | MB_ICONWARNING,
);
}
}
fn show_menu(&self) {
unsafe {
let Ok(menu) = CreatePopupMenu() else { return };
let result = (|| {
AppendMenuW(menu, MF_STRING, OPEN as usize, w!("Ouvrir"))?;
AppendMenuW(menu, MF_STRING, QUIT as usize, w!("Quitter"))?;
let icon = NOTIFYICONIDENTIFIER {
cbSize: size_of::<NOTIFYICONIDENTIFIER>() as u32,
hWnd: self.hwnd,
uID: ICON_ID,
..Default::default()
};
let point = match Shell_NotifyIconGetRect(&icon) {
Ok(rect) => POINT {
x: rect.left,
y: rect.top,
},
Err(_) => {
let mut point = POINT::default();
GetCursorPos(&mut point)?;
point
}
};
let _ = SetForegroundWindow(self.hwnd);
Ok::<_, windows::core::Error>(
TrackPopupMenu(
menu,
TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON,
point.x,
point.y,
None,
self.hwnd,
None,
)
.0 as u32,
)
})();
let _ = DestroyMenu(menu);
let _ = PostMessageW(Some(self.hwnd), WM_NULL, WPARAM(0), LPARAM(0));
match result {
Ok(OPEN) => self.open(),
Ok(QUIT) => {
// Destroying the window takes GPUI's normal exit path without another close request.
let _ = DestroyWindow(self.hwnd);
}
_ if self.hidden.get() => {
let _ = Shell_NotifyIconW(NIM_SETFOCUS, &self.icon_data());
}
_ => {}
}
}
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
data: usize,
) -> LRESULT {
let data = data as *const Tray;
// Native calls can dispatch nested messages, including destruction. Keep our own reference
// for the messages we handle and leave the high-frequency messages on the default path.
let taskbar_created = unsafe { (*data).taskbar_created };
if !matches!(
message,
WM_CLOSE | WM_ENDSESSION | WM_NCDESTROY | TRAY_MESSAGE
) && message != taskbar_created
{
return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
}
let tray = unsafe {
Rc::increment_strong_count(data);
Rc::from_raw(data)
};
match message {
WM_CLOSE if tray.enabled.get() => {
if !tray.hidden.get() {
if tray.add_icon() {
tray.hidden.set(true);
let _ = unsafe { ShowWindow(hwnd, SW_HIDE) };
} else {
tray.report_unavailable();
}
}
return LRESULT(0);
}
TRAY_MESSAGE => {
if tray.hidden.get() && (lparam.0 as u32 >> 16) == ICON_ID {
match lparam.0 as u32 & 0xffff {
WM_CONTEXTMENU => tray.show_menu(),
NIN_SELECT | NIN_KEYSELECT => tray.open(),
_ => {}
}
}
return LRESULT(0);
}
WM_ENDSESSION if wparam.0 != 0 => tray.remove_icon(),
WM_NCDESTROY => unsafe {
tray.remove_icon();
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
drop(Rc::from_raw(data));
},
message if message == taskbar_created && tray.hidden.get() => {
// Explorer discards notification icons when it recreates the taskbar.
if !tray.add_icon() {
tray.open();
tray.report_unavailable();
}
return LRESULT(0);
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}