From d7bd69c35d7c12d593fda74e2038b9f826afd6ba Mon Sep 17 00:00:00 2001
From: Nessar
Date: Wed, 18 Nov 2026 00:36:15 +0100
Subject: [PATCH] Add tray and theme settings (#21)
---
Cargo.lock | 2 +
crates/app/Cargo.toml | 8 ++
crates/app/src/main.rs | 44 +++---
crates/app/src/settings.rs | 160 ++++++++++++++++++++-
crates/app/src/tray.rs | 286 +++++++++++++++++++++++++++++++++++++
crates/core/src/config.rs | 55 ++++++-
crates/core/src/lib.rs | 2 +-
7 files changed, 520 insertions(+), 37 deletions(-)
create mode 100644 crates/app/src/tray.rs
diff --git a/Cargo.lock b/Cargo.lock
index 96024a7..e629edc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -225,6 +225,8 @@ dependencies = [
"embed-resource",
"gpui-kit",
"gpui-pre",
+ "raw-window-handle",
+ "windows 0.62.2",
]
[[package]]
diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml
index e6e583b..b170172 100644
--- a/crates/app/Cargo.toml
+++ b/crates/app/Cargo.toml
@@ -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.
diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs
index a6cd9d5..8b40fa3 100644
--- a/crates/app/src/main.rs
+++ b/crates/app/src/main.rs
@@ -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> {
+fn startup() -> Result, 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> {
};
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> {
})
}
-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),
diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs
index 376b4f0..6e8a7fe 100644
--- a/crates/app/src/settings.rs
+++ b/crates/app/src/settings.rs
@@ -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,
- _subscription: Subscription,
+ preference_error: Option<&'static str>,
+ tray: Option>,
+ _subscriptions: [Subscription; 2],
}
impl EventEmitter for KeyForm {}
@@ -63,6 +99,12 @@ impl KeyForm {
window: &mut Window,
cx: &mut Context,
) -> 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.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,
+ ) {
+ 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) -> 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) {
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);
+ }
+ }
+}
diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs
new file mode 100644
index 0000000..814b83c
--- /dev/null
+++ b/crates/app/src/tray.rs
@@ -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,
+ hidden: Cell,
+ _quit: Subscription,
+}
+
+impl Tray {
+ pub fn install_saved(window: &mut Window, enabled: bool, cx: &mut App) -> Option> {
+ 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> {
+ 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| {
+ 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.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::() 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::() 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) }
+}
diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs
index 273f4f2..273cce4 100644
--- a/crates/core/src/config.rs
+++ b/crates/core/src/config.rs
@@ -13,6 +13,35 @@ pub struct Config {
pub riot_id: String,
#[serde(default = "default_region")]
pub region: String,
+ #[serde(flatten)]
+ pub preferences: Preferences,
+ #[serde(flatten)]
+ other: toml::Table,
+}
+
+#[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 {
+ #[default]
+ System,
+ Light,
+ Dark,
}
fn default_region() -> String {
@@ -37,6 +66,8 @@ impl Config {
riot_api_key: String::new(),
riot_id: String::new(),
region: default_region(),
+ preferences: Preferences::default(),
+ other: toml::Table::new(),
})
}
@@ -76,6 +107,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_eq!(config.preferences.theme, ThemePreference::System);
}
#[test]
@@ -112,21 +145,29 @@ mod tests {
("", "", "europe")
);
assert!(!dir.path().join("config.toml").exists());
+ assert!(config.preferences.close_to_tray);
+ assert_eq!(config.preferences.theme, ThemePreference::System);
}
#[test]
fn saved_settings_load_back() {
let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("nested").join("config.toml");
- let config = Config {
- riot_api_key: "RGAPI-secret".into(),
- riot_id: "Joueur#EUW".into(),
- region: "americas".into(),
+ let path = dir.path().join("config.toml");
+ std::fs::write(
+ &path,
+ "riot_api_key = \"RGAPI-secret\"\nriot_id = \"Joueur#EUW\"\nregion = \"americas\"\n\n[other]\nvalue = 42\n",
+ )
+ .unwrap();
+ let mut config = Config::load(&path).unwrap();
+ config.preferences = Preferences {
+ 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_eq!(loaded.other["other"]["value"].as_integer(), Some(42));
assert_eq!(loaded.riot_api_key, "RGAPI-secret");
assert_eq!(
(loaded.riot_id.as_str(), loaded.region.as_str()),
@@ -143,6 +184,8 @@ mod tests {
riot_api_key: "RGAPI-secret".into(),
riot_id: String::new(),
region: "europe".into(),
+ preferences: Preferences::default(),
+ other: toml::Table::new(),
};
let Err(err) = config.save(&blocker.join("config.toml")) else {
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 3b01f4f..010a1df 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -15,7 +15,7 @@ mod tracker;
pub use champion_search::ChampionSearch;
pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon};
pub use client::{ClientError, GameClientSource, GamePhase, Gameflow};
-pub use config::{Config, data_dir};
+pub use config::{Config, Preferences, ThemePreference, data_dir};
pub use date::Date;
pub use error::{Error, SourceError};
pub use follow::{MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem};