From aac2f4212c5f0f5a51d1000de509f3a730d14090 Mon Sep 17 00:00:00 2001 From: TO Date: Sun, 22 Nov 2026 00:50:07 +0100 Subject: [PATCH] Offer to launch Arena Tracker at Windows logon (#67) Windows alone holds the choice: the Run entry, unless the Task Manager disabled it under StartupApproved\Run. The settings read both when they open; switching on writes the entry and approves it again. Started with --logon, the app opens hidden in the notification area, or minimized when there is no tray icon, and paints no page in the first frame, so no portrait is decoded before the window is shown. An update ready at logon is applied silently and reopens hidden. Installing or uninstalling removes the entry; updates keep it. Co-Authored-By: Claude Opus 5.5 --- crates/app/Cargo.toml | 1 + crates/app/src/logon.rs | 285 +++++++++++++++++++++++++++++++++++++ crates/app/src/main.rs | 45 ++++-- crates/app/src/release.rs | 45 +++--- crates/app/src/settings.rs | 96 ++++++++++++- crates/app/src/tray.rs | 55 ++++++- docs/paquets-windows.md | 10 ++ 7 files changed, 507 insertions(+), 30 deletions(-) create mode 100644 crates/app/src/logon.rs diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 33d147e..5b563c4 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -19,6 +19,7 @@ raw-window-handle = "0.6" windows = { version = "0.62", features = [ "Win32_Security", "Win32_System_LibraryLoader", + "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", diff --git a/crates/app/src/logon.rs b/crates/app/src/logon.rs new file mode 100644 index 0000000..442157c --- /dev/null +++ b/crates/app/src/logon.rs @@ -0,0 +1,285 @@ +//! Launching Arena Tracker at the user's Windows logon (#67). +//! +//! Windows alone holds the choice, never `config.toml`: the logon starts the command of an +//! entry under `Run` unless the Task Manager's « Applications de démarrage » disabled it, which +//! it records under `StartupApproved\Run` without deleting the entry. Enabling the launch here +//! approves the entry again: the latest explicit choice wins. + +use std::path::Path; + +use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS}; +use windows::Win32::System::Registry::{ + HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_BINARY, REG_OPTION_NON_VOLATILE, REG_SZ, + REG_VALUE_TYPE, RRF_RT_REG_BINARY, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, + RegDeleteKeyValueW, RegGetValueW, RegSetValueExW, +}; +use windows::core::{HSTRING, Result, w}; + +use crate::release; + +/// Given by the entry's command: the app starts hidden (`tray::start_hidden`). +pub const ARG: &str = "--logon"; +/// The entry's value name in both keys. +const NAME: windows::core::PCWSTR = w!("ArenaTracker"); +/// What the Task Manager writes for an enabled entry; an odd first byte disables it. +const APPROVED: [u8; 12] = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + +/// Whether Windows started this process at logon. +pub fn launched_at_logon() -> bool { + std::env::args_os().nth(1).is_some_and(|arg| arg == ARG) +} + +/// The two keys of the entry, under `HKEY_CURRENT_USER`. +struct Keys { + run: HSTRING, + approved: HSTRING, +} + +impl Keys { + fn current_user() -> Keys { + Keys::under(r"Software\Microsoft\Windows\CurrentVersion") + } + + /// `Run` and `Explorer\StartupApproved\Run` under `root`, as Windows lays them out. + fn under(root: &str) -> Keys { + Keys { + run: format!(r"{root}\Run").into(), + approved: format!(r"{root}\Explorer\StartupApproved\Run").into(), + } + } + + /// Removes the entry and its approval, if they exist. + fn remove(&self) -> Result<()> { + for key in [&self.run, &self.approved] { + let deleted = unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, key, NAME) }; + if deleted != ERROR_SUCCESS && deleted != ERROR_FILE_NOT_FOUND { + return Err(deleted.into()); + } + } + Ok(()) + } +} + +/// The launch at the user's Windows logon. +pub struct LogonLaunch { + keys: Keys, + /// `None` outside an installed version: nothing to start that would outlive this build. + command: Option, +} + +impl LogonLaunch { + /// The entry of this Windows user, starting the installed executable. + pub fn installed() -> LogonLaunch { + LogonLaunch { + keys: Keys::current_user(), + command: std::env::current_exe() + .ok() + .and_then(|exe| installed_command(release::VERSION, &exe)), + } + } + + /// Only an installed version offers the launch. + pub fn available(&self) -> bool { + self.command.is_some() + } + + /// Whether the logon starts Arena Tracker: an entry the Task Manager did not + /// disable. Two registry reads, done when the settings are shown, never per frame. + pub fn enabled(&self) -> bool { + let found = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + &self.keys.run, + NAME, + RRF_RT_REG_SZ, + None, + None, + None, + ) + }; + if found != ERROR_SUCCESS { + return false; + } + let mut data = [0u8; 64]; + let mut size = data.len() as u32; + let read = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + &self.keys.approved, + NAME, + RRF_RT_REG_BINARY, + None, + Some(data.as_mut_ptr().cast()), + Some(&mut size), + ) + }; + // No approval: the Task Manager never touched the entry. A value longer than any it + // writes is not one of its choices either. + read != ERROR_SUCCESS || approved(&data[..size as usize]) + } + + /// Writes or removes the entry. Enabling also approves it, undoing a Task Manager choice. + pub fn set(&self, enabled: bool) -> Result<()> { + if !enabled { + return self.keys.remove(); + } + let Some(command) = &self.command else { + return Err(ERROR_FILE_NOT_FOUND.into()); + }; + let text: Vec = (command.encode_utf16().chain([0])) + .flat_map(u16::to_le_bytes) + .collect(); + set_value(&self.keys.run, REG_SZ, &text)?; + set_value(&self.keys.approved, REG_BINARY, &APPROVED) + } +} + +/// Removes this user's entry: an installation, or an uninstallation, starts without it. +pub fn forget() -> Result<()> { + Keys::current_user().remove() +} + +/// The entry's command for an installed version: its executable in `current\`, a path that +/// Velopack keeps across updates. A development build has no version and runs elsewhere. +fn installed_command(version: Option<&str>, exe: &Path) -> Option { + version?; + if exe.parent()?.file_name()? != "current" { + return None; + } + Some(format!("\"{}\" {ARG}", exe.to_str()?)) +} + +/// The Task Manager marks a disabled entry with an odd first byte (3, or 7 for some entries). +fn approved(value: &[u8]) -> bool { + value.first().is_none_or(|byte| byte & 1 == 0) +} + +fn set_value(subkey: &HSTRING, kind: REG_VALUE_TYPE, data: &[u8]) -> Result<()> { + let mut key = HKEY::default(); + unsafe { + RegCreateKeyExW( + HKEY_CURRENT_USER, + subkey, + None, + None, + REG_OPTION_NON_VOLATILE, + KEY_SET_VALUE, + None, + &mut key, + None, + ) + .ok()?; + let written = RegSetValueExW(key, NAME, None, kind, Some(data)); + let _ = RegCloseKey(key); + written.ok() + } +} + +#[cfg(test)] +pub(crate) mod tests { + use std::path::Path; + + use windows::Win32::System::Registry::{HKEY_CURRENT_USER, RegDeleteTreeW}; + use windows::core::HSTRING; + + use super::{Keys, LogonLaunch, REG_BINARY, approved, installed_command, set_value}; + + /// A scratch copy of the two keys under the current user, removed when dropped. + pub(crate) struct Scratch { + root: HSTRING, + approved: HSTRING, + } + + impl Scratch { + /// The launch of an installed version (`installed`) or of a development build, on + /// scratch keys named after the test. + pub(crate) fn launch(name: &str, installed: bool) -> (Scratch, LogonLaunch) { + let root = format!( + r"Software\nessar-arena-tracker-tests\{name}-{}", + std::process::id() + ); + let keys = Keys::under(&root); + let scratch = Scratch { + root: root.as_str().into(), + approved: keys.approved.clone(), + }; + scratch.drop_tree(); + let command = installed.then_some(r#""C:\Arena\current\arena-tracker.exe" --logon"#); + let launch = LogonLaunch { + keys, + command: command.map(String::from), + }; + (scratch, launch) + } + + /// « Désactiver » in the Task Manager's « Applications de démarrage ». + pub(crate) fn disable_in_task_manager(&self) { + let disabled = [3, 0, 0, 0, 0xa0, 0x6e, 0x4b, 0x2c, 0x5e, 0x4d, 0xdb, 0x01]; + set_value(&self.approved, REG_BINARY, &disabled).unwrap(); + } + + fn drop_tree(&self) { + let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &self.root) }; + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + self.drop_tree(); + } + } + + #[test] + fn the_entry_follows_the_switch_and_the_task_manager_choice() { + let (scratch, launch) = Scratch::launch("follows", true); + assert!(!launch.enabled(), "a first installation starts disabled"); + + launch.set(true).unwrap(); + assert!(launch.enabled()); + + scratch.disable_in_task_manager(); + assert!( + !launch.enabled(), + "the settings show the Task Manager's choice" + ); + + launch.set(true).unwrap(); + assert!(launch.enabled(), "enabling here approves the entry again"); + + launch.set(false).unwrap(); + assert!(!launch.enabled()); + // Nothing left behind, and removing what is gone is not an error. + launch.set(false).unwrap(); + } + + #[test] + fn a_build_outside_an_installation_cannot_enable_the_launch() { + let (_scratch, launch) = Scratch::launch("unavailable", false); + assert!(!launch.available()); + assert!(launch.set(true).is_err()); + assert!(!launch.enabled()); + } + + #[test] + fn only_an_installed_version_in_current_gets_a_command() { + let installed = + Path::new(r"C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe"); + assert_eq!( + installed_command(Some("1.0.0"), installed).as_deref(), + Some(r#""C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe" --logon"#) + ); + assert_eq!(installed_command(None, installed), None); + let built = + Path::new(r"C:\Users\A\AppData\Local\arena-tracker\target\release\arena-tracker.exe"); + assert_eq!(installed_command(Some("1.0.0"), built), None); + } + + #[test] + fn an_odd_first_byte_marks_a_disabled_entry() { + assert!(approved(&[2, 0, 0])); + assert!(approved(&[6, 0])); + assert!(approved(&[])); + assert!(!approved(&[3, 0, 0])); + assert!(!approved(&[7])); + } +} diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 0b323a4..2b83a00 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -7,6 +7,7 @@ mod card_images; mod card_lift; mod card_order; mod champion_table; +mod logon; mod motion; mod page; #[cfg(feature = "profile")] @@ -53,13 +54,16 @@ struct RootView { /// The configured Riot ID, used when the game client is closed on first launch. fallback_riot_id: String, tx: Sender, + /// Started hidden at logon: the first frame, which GPUI draws as the window + /// opens, paints no page, so no portrait is decoded before the window is shown. + blank: bool, _form_events: Subscription, _champ_select: Subscription, _sort: Subscription, } impl RootView { - fn new(setup: Setup, window: &mut Window, cx: &mut Context) -> Self { + fn new(setup: Setup, hidden: bool, window: &mut Window, cx: &mut Context) -> Self { let Setup { tracker, riot_id, @@ -134,6 +138,14 @@ impl RootView { spawn_follower(tracker.clone(), riot_id.clone(), tx.clone()); Screen::Page }; + if hidden { + // Runs once GPUI's first frame is drawn. A hidden or minimized window gets no + // other frame: the page is painted when the window is shown. + cx.defer_in(window, |this, _, cx| { + this.blank = false; + cx.notify(); + }); + } RootView { page, form, @@ -142,6 +154,7 @@ impl RootView { tracker, fallback_riot_id: riot_id, tx, + blank: hidden, _form_events: form_events, _champ_select: champ_select, _sort: sort, @@ -155,6 +168,8 @@ impl RootView { fn open_settings(&mut self, window: &mut Window, cx: &mut Context) { if self.screen == Screen::Page { self.screen = Screen::Settings; + // Windows holds the launch at logon: read it as the settings open. + self.form.update(cx, |form, _| form.read_logon_launch()); self.page.update(cx, |page, cx| page.hidden(window, cx)); self.focus.focus(window, cx); cx.notify(); @@ -188,6 +203,7 @@ impl Render for RootView { .on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx))) }); let content = match self.screen { + _ if self.blank => div().into_any_element(), Screen::Page => self.page.clone().into_any_element(), Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(), }; @@ -293,8 +309,10 @@ fn main() { else { return; }; + // Started by the logon entry: hidden, or minimized (#67). + let at_logon = logon::launched_at_logon(); // 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 { + let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else { return; }; let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets); @@ -304,17 +322,16 @@ fn main() { theme::init(cx); #[cfg(feature = "profile")] profile::start(cx); + let bounds = Bounds::centered(None, size(px(1280.), px(860.)), 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_bounds: Some(WindowBounds::Windowed(bounds)), window_min_size: Some(MIN_WINDOW_SIZE), + show: !at_logon, + focus: !at_logon, ..Default::default() }; match startup() { @@ -324,7 +341,12 @@ fn main() { gpui_kit::open_window(options, cx, |window, cx| { single_instance::accept_relaunches(window); motion::follow_windows_setting(window, cx); - cx.new(|cx| RootView::new(setup, window, cx)) + // The settings form installs the tray that hides the window. + let root = cx.new(|cx| RootView::new(setup, at_logon, window, cx)); + if at_logon { + tray::start_hidden(window, bounds); + } + root }) .map(drop) } @@ -339,6 +361,9 @@ fn main() { .detach(); // Without a readable configuration the one-time notice could not be recorded. tray::Tray::install_saved(window, preferences.close_to_tray, None, cx); + if at_logon { + tray::start_hidden(window, bounds); + } cx.new(|cx| Unavailable { lines, focus: initial_focus(window, cx), @@ -382,7 +407,7 @@ mod tests { 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)) + cx.new(|cx| RootView::new(setup, false, window, cx)) }) .unwrap() }); @@ -464,7 +489,7 @@ mod tests { store: KeyStore::new(path.to_path_buf(), config, api), }; gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { - cx.new(|cx| RootView::new(setup, window, cx)) + cx.new(|cx| RootView::new(setup, false, window, cx)) }) .unwrap() }); diff --git a/crates/app/src/release.rs b/crates/app/src/release.rs index f0aebd6..5d0bdd8 100644 --- a/crates/app/src/release.rs +++ b/crates/app/src/release.rs @@ -15,6 +15,7 @@ use windows::Win32::System::Threading::{ }; use windows::core::PWSTR; +use crate::logon; use crate::single_instance::owned; /// This executable's release version; `None` for a development build, which never updates. @@ -33,12 +34,14 @@ pub fn handle_command() { let mut args = std::env::args_os().skip(1); let Some(command) = args.next() else { return }; match command.to_str() { - Some( - "--veloapp-install" - | "--veloapp-updated" - | "--veloapp-obsolete" - | "--veloapp-uninstall", - ) => { + Some("--veloapp-updated" | "--veloapp-obsolete") => { + std::process::exit(0); + } + Some("--veloapp-install" | "--veloapp-uninstall") => { + // Otherwise each logon would start a deleted executable, and a reinstallation, even + // over an installation its uninstallation did not clean, would launch at logon + // before anyone chose it. An update keeps the choice: `current\` keeps its path. + let _ = logon::forget(); std::process::exit(0); } Some("--verify-release") => { @@ -102,8 +105,9 @@ pub fn download_update(channel: UpdateChannel) -> Option { /// Before the app loads, in the single instance only: hands the kept update of the chosen /// channel to Update.exe once. `Break`: Update.exe replaces this version and opens the app. -/// `Continue`: load the app, with the notice to show if there is one. -pub fn update_at_launch() -> ControlFlow<(), Option> { +/// `Continue`: load the app, with the notice to show if there is one. At logon, the version +/// Update.exe opens, new or this one again, starts hidden too. +pub fn update_at_launch(at_logon: bool) -> ControlFlow<(), Option> { let Some((dir, key, version)) = update_context() else { return ControlFlow::Continue(None); }; @@ -121,7 +125,7 @@ pub fn update_at_launch() -> ControlFlow<(), Option> { &key, channel, version, - start_installer, + |package| start_installer(package, at_logon), installer_exit, ) .map_continue(|error| error.map(|error| error.to_string())) @@ -131,8 +135,10 @@ pub fn update_at_launch() -> ControlFlow<(), Option> { /// Hashes the package on the calling thread: a few tens of milliseconds for a full package. pub fn restart_to_update(channel: UpdateChannel) -> Result<(), String> { let (dir, key, version) = update_context().ok_or("Cette version ne se met pas à jour.")?; - arena_tracker_core::restart_to_update(&dir, &key, channel, version, start_installer) - .map_err(|e| e.to_string()) + arena_tracker_core::restart_to_update(&dir, &key, channel, version, |package| { + start_installer(package, false) + }) + .map_err(|e| e.to_string()) } /// Update.exe at the installation's root, next to `current\arena-tracker.exe`. @@ -144,18 +150,23 @@ fn installer() -> io::Result { /// Starts Velopack's installer on an authenticated package, which it reads in place: it waits /// for this process to exit, replaces `current\` and opens the app once, this version again if -/// it fails (ADR-0005, `docs/paquets-windows.md`). -fn start_installer(package: &Path) -> io::Result { - let child = Command::new(installer()?) +/// it fails (ADR-0005, `docs/paquets-windows.md`). At logon, Velopack 1.2.161 +/// shows neither its progress window nor its dialogs (`--silent`, which must come before +/// `--`), and hands the arguments after `--` to the version it opens, in both cases. +fn start_installer(package: &Path, at_logon: bool) -> io::Result { + let mut command = Command::new(installer()?); + command .args([ "apply", "--waitPid", &std::process::id().to_string(), "--package", ]) - .arg(package) - .creation_flags(CREATE_NO_WINDOW.0) - .spawn()?; + .arg(package); + if at_logon { + command.args(["--silent", "--", logon::ARG]); + } + let child = command.creation_flags(CREATE_NO_WINDOW.0).spawn()?; Ok(child.id()) } diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index 84effa5..12f98d9 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -12,9 +12,10 @@ use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::input::{Input, InputEvent, InputState}; 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::component::{ActiveTheme as _, Disableable as _, StyledExt as _, Theme, ThemeMode}; use gpui_kit::*; +use crate::logon::LogonLaunch; use crate::release::{self, channel}; use crate::tray::{Tray, UNAVAILABLE}; use crate::worker::{RefreshGate, UpdateChecked, spawn_update_check}; @@ -32,6 +33,10 @@ const CHANNELS: [(UpdateChannel, &str); 2] = [ ]; const STABLE_AFTER_BETA: &str = "La bêta installée reste en place jusqu’à une version stable plus récente."; +const LOGON_LABEL: &str = "Lancer à l’ouverture de session Windows"; +// Not « Disponible »: the interface word of a Pickable champion (CONTEXT.md). +const LOGON_UNAVAILABLE: &str = "Réservé à la version installée."; +const LOGON_ERROR: &str = "Impossible de modifier le lancement à l’ouverture de session."; fn theme_mode(preference: ThemePreference, system: ThemeMode) -> ThemeMode { match preference { @@ -110,6 +115,10 @@ pub struct KeyForm { error: Option, preference_error: Option, tray: Option>, + logon_launch: LogonLaunch, + /// What Windows said when the settings were last shown or changed: it holds the choice. + /// Read only then, not at launch: the settings always open through `read_logon_launch`. + launches_at_logon: bool, /// The tray reports here that it showed its one-time notice. notice_shown: Sender<()>, /// « Mise à jour prête » with the version downloaded and authenticated for the chosen channel. @@ -180,6 +189,7 @@ impl KeyForm { this.save(window, cx); } }); + let logon_launch = LogonLaunch::installed(); let mut form = KeyForm { first_launch, store, @@ -187,6 +197,8 @@ impl KeyForm { error: None, preference_error: None, tray, + launches_at_logon: false, + logon_launch, notice_shown, ready: None, update_checks: RefreshGate::default(), @@ -292,6 +304,19 @@ impl KeyForm { cx.notify(); } + /// Reads the choice again: the Task Manager may have changed it since. + pub fn read_logon_launch(&mut self) { + self.launches_at_logon = self.logon_launch.enabled(); + } + + /// Writes the choice to Windows. On a refusal the switch shows what Windows holds. + fn set_logon_launch(&mut self, enabled: bool, cx: &mut Context) { + let written = self.logon_launch.set(enabled); + self.read_logon_launch(); + self.preference_error = written.is_err().then(|| LOGON_ERROR.into()); + cx.notify(); + } + /// Saves the cards' sort with the other preferences. Nothing else changes, and a failed /// write only shows the usual message in the settings: the page keeps the choice. pub fn save_champion_sort(&mut self, sort: ChampionSort, cx: &mut Context) { @@ -313,9 +338,28 @@ impl KeyForm { fn preferences(&self, cx: &mut Context) -> impl IntoElement { let preferences = self.store.config.preferences; let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger); + let logon_available = self.logon_launch.available(); div() .v_flex() .gap_3() + .child( + div() + .v_flex() + .gap_1() + .child( + Switch::new("launch-at-logon") + .label(LOGON_LABEL) + .checked(self.launches_at_logon) + .disabled(!logon_available) + .on_change(cx.listener(|this, enabled, _, cx| { + this.set_logon_launch(*enabled, cx); + })), + ) + .children( + (!logon_available) + .then(|| div().text_color(muted).child(LOGON_UNAVAILABLE)), + ), + ) .child( Switch::new("close-to-tray") .label("Fermer dans la zone de notification") @@ -518,6 +562,7 @@ mod tests { use gpui_kit::{AppContext as _, TestAppContext, VisualTestContext, WindowOptions}; use super::{KeyForm, KeyStore, ThemeMode, ThemePreference, theme_mode}; + use crate::logon::tests::Scratch; use crate::worker::UpdateChecked; #[gpui::test] @@ -592,6 +637,55 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[gpui::test] + fn the_logon_switch_shows_what_windows_holds(cx: &mut TestAppContext) { + cx.update(gpui_kit::init); + let (window, form) = cx.update(|cx| { + let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap(); + let api = Arc::new(RiotApi::new(String::new(), &config.region)); + let store = KeyStore::new("unused.toml".into(), config, api); + gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { + cx.new(|cx| KeyForm::new(store, false, window, cx)) + }) + .unwrap() + }); + let cx = &mut VisualTestContext::from_window(window, cx); + let (scratch, installed) = Scratch::launch("settings", true); + let (_dev_scratch, development) = Scratch::launch("settings-dev", false); + form.update(cx, |form, cx| { + form.logon_launch = installed; + form.read_logon_launch(); + assert!( + !form.launches_at_logon, + "a first installation starts disabled" + ); + form.set_logon_launch(true, cx); + assert!(form.launches_at_logon); + assert_eq!(form.preference_error, None); + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + + // Disabled in the Task Manager while the settings were closed, then opened again. + scratch.disable_in_task_manager(); + form.update(cx, |form, cx| { + form.read_logon_launch(); + assert!(!form.launches_at_logon); + form.set_logon_launch(true, cx); + assert!(form.launches_at_logon, "switching it on approves it again"); + form.set_logon_launch(false, cx); + assert!(!form.launches_at_logon); + }); + + // Windows refuses: the switch shows what it holds, and the settings say so. + form.update(cx, |form, cx| { + form.logon_launch = development; + form.set_logon_launch(true, cx); + assert!(!form.launches_at_logon); + assert_eq!(form.preference_error.as_deref(), Some(super::LOGON_ERROR)); + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + #[test] fn system_tracks_the_current_appearance_and_manual_choices_override_it() { for system in [ThemeMode::Light, ThemeMode::Dark] { diff --git a/crates/app/src/tray.rs b/crates/app/src/tray.rs index 167f3e8..7113464 100644 --- a/crates/app/src/tray.rs +++ b/crates/app/src/tray.rs @@ -6,10 +6,10 @@ use std::{ }; use gpui_kit::base::async_util::Sender; -use gpui_kit::{App, PromptLevel, Subscription, Window}; +use gpui_kit::{App, Bounds, Pixels, PromptLevel, Subscription, Window}; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; use windows::Win32::{ - Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, WPARAM}, + Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}, System::LibraryLoader::GetModuleHandleW, UI::{ Shell::{ @@ -261,6 +261,57 @@ fn installed_tray(hwnd: HWND) -> Option> { .then(|| unsafe { retain(data as *const Tray) }) } +/// Leaves a window opened hidden at logon (`show: false`) in the notification +/// area, without the one-time notice, or minimized in the taskbar when the icon cannot be added: +/// no tray, or a taskbar not created yet. Never running with neither icon nor window. +pub fn start_hidden(window: &Window, bounds: Bounds) { + let Some(hwnd) = window_hwnd(window) else { + // Nothing to hide it with: shown and placed by GPUI, rather than out of reach. + window.activate_window(); + return; + }; + let in_tray = installed_tray(hwnd).is_some_and(|tray| { + let added = tray.add_icon(); + tray.hidden.set(added); + added + }); + let command = if in_tray { SW_HIDE } else { SW_SHOWMINNOACTIVE }; + let placed = + normal_placement(hwnd, bounds, window.scale_factor()).is_some_and(|mut placement| { + placement.showCmd = command.0 as u32; + unsafe { SetWindowPlacement(hwnd, &placement) }.is_ok() + }); + if !placed && !in_tray { + let _ = unsafe { ShowWindow(hwnd, SW_SHOWMINNOACTIVE) }; + } +} + +/// GPUI places a window opened hidden only when it activates it, which the notification area +/// and the champ select never ask for: its normal place is `bounds` here, set as GPUI sets it +/// (`retrieve_window_placement`), with the frame around the client area split on both sides. +fn normal_placement(hwnd: HWND, bounds: Bounds, scale: f32) -> Option { + let mut placement = WINDOWPLACEMENT { + length: size_of::() as u32, + ..Default::default() + }; + let (mut frame, mut client) = (RECT::default(), RECT::default()); + unsafe { + GetWindowPlacement(hwnd, &mut placement).ok()?; + GetWindowRect(hwnd, &mut frame).ok()?; + GetClientRect(hwnd, &mut client).ok()?; + } + let width = (frame.right - frame.left) - (client.right - client.left); + let height = (frame.bottom - frame.top) - (client.bottom - client.top); + let bounds = bounds.to_device_pixels(scale); + placement.rcNormalPosition = RECT { + left: bounds.left().0 - width / 2, + top: bounds.top().0 - height / 2, + right: bounds.right().0 + (width - width / 2), + bottom: bounds.bottom().0 + (height - height / 2), + }; + Some(placement) +} + pub fn reopen(hwnd: HWND) { match installed_tray(hwnd) { Some(tray) => tray.open(), diff --git a/docs/paquets-windows.md b/docs/paquets-windows.md index c128529..11d5c1b 100644 --- a/docs/paquets-windows.md +++ b/docs/paquets-windows.md @@ -49,6 +49,16 @@ Les Parties sont écrites une à une dans SQLite en mode WAL, et la configuratio Limites acceptées de Velopack 1.2.161 : son remplacement n’a pas de retour arrière. `current` est renommé, puis le dossier extrait prend sa place. Une coupure entre ces deux renommages, ou un fichier extrait verrouillé plus de 30 s, laisse l’installation sans `current` ; une réinstallation la répare et les données de `%APPDATA%\arena-tracker` restent intactes. Un fichier verrouillé dans `current` fait au contraire échouer le premier renommage, et l’ancienne version reste en place. Velopack supprime aussi le paquet qu’il ne parvient pas à ouvrir ; la vérification suivante le télécharge de nouveau. Entre la vérification et la lecture par `Update.exe`, seul un programme du même compte Windows peut remplacer le paquet, et ce compte peut tout aussi bien remplacer l’exécutable ([ADR-0005](adr/0005-package-with-velopack-and-our-own-signed-manifest.md)). +## Lancement à l’ouverture de session + +Les Paramètres proposent « Lancer à l’ouverture de session Windows » (#67), désactivé à la première installation. Windows seul garde ce choix, jamais `config.toml`. L’interrupteur l’affiche activé si la valeur `ArenaTracker` existe sous `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` et que le Gestionnaire des tâches ne l’a pas désactivée. Ce dernier ne supprime pas l’entrée : il note son choix dans la valeur de même nom sous `HKCU\…\Explorer\StartupApproved\Run`, dont un premier octet impair signifie « désactivé ». Les Paramètres relisent ces deux clés à chaque ouverture. Activer écrit l’entrée `"\current\arena-tracker.exe" --logon` et remet l’approbation à « activé » : le dernier choix explicite l’emporte. Désactiver supprime les deux valeurs. Si Windows refuse l’écriture, l’interrupteur revient à l’état réel et les Paramètres affichent « Impossible de modifier le lancement à l’ouverture de session. ». Une version de développement n’a pas d’installation à lancer : l’interrupteur y est désactivé, avec « Réservé à la version installée. » (« Disponible » est le mot d’un champion Pickable, `CONTEXT.md`). + +Lancée avec `--logon`, l’application ouvre sa fenêtre sans l’afficher et la laisse cachée dans la zone de notification, sans avis. Si « Fermer dans la zone de notification » est désactivé, ou si l’icône ne peut pas s’ajouter (barre des tâches pas encore créée), elle la laisse réduite dans la barre des tâches. GPUI ne place une fenêtre ouverte cachée qu’en l’activant, ce que ni la zone de notification ni la sélection des champions ne font : l’application lui donne donc elle-même sa place normale, comme GPUI. Le premier rendu, que GPUI dessine à l’ouverture, ne peint pas la page ; une fenêtre cachée ou réduite n’en reçoit pas d’autre. Les Parties sont suivies et importées comme d’habitude, et une sélection Arena ramène la fenêtre, mais aucun portrait n’est décodé avant le premier affichage. + +Une mise à jour prête au lancement d’ouverture de session est appliquée avec `Update.exe apply --waitPid --package --silent -- --logon`. `--silent` retire la fenêtre de progression et les dialogues de Velopack. Velopack 1.2.161 passe les arguments placés après `--` à la version qu’il ouvre, la nouvelle comme l’ancienne après un échec : elle démarre cachée à son tour. [Arguments de apply](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/update.rs) · [Fenêtre de progression](https://github.com/velopack/velopack/blob/1.2.161/src/l18n/src/progress.rs) + +Le chemin `current\arena-tracker.exe` ne change pas d’une mise à jour à l’autre : l’entrée et le choix sont gardés. La désinstallation appelle `arena-tracker.exe --veloapp-uninstall`, et l’installation `--veloapp-install` : les deux suppriment les deux valeurs avant de sortir. Sans cela, chaque ouverture de session tenterait de lancer un exécutable supprimé, et une réinstallation retrouverait l’option activée, y compris par-dessus une installation que sa désinstallation n’a pas nettoyée. Une mise à jour (`--veloapp-updated`) n’y touche pas. + ## Validation du chemin de démarrage L’essai Windows de vpk 1.2.161 a installé une application témoin sous un jeton non élevé. Le raccourci créé par le packer ciblait directement `current\Trial.exe` et a ouvert cette application même avec le paquet local verrouillé en accès exclusif. La désinstallation a ensuite supprimé le raccourci.