diff --git a/CHANGELOG.md b/CHANGELOG.md index 5150af0..eadc134 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ a section is written. ## [Unreleased] +## [0.5.0] - 2026-11-16 + +Windows' Startup list starts the watcher now, with a switch in Settings, +instead of a scheduled task that Office's updates could end; the startup +commands are renamed, and every release file is attested. + ### Added - Each release file comes with GitHub's attestation that the release workflow @@ -26,14 +32,20 @@ a section is written. ### Changed - Windows starts the watcher at logon from your `Run` key instead of a - scheduled task; an upgrade removes the old task. + scheduled task, a few seconds later than the task did. Office's updates + ended what the task started, the watcher among them, and spared what the + `Run` key started over a month of them. An upgrade removes the old task and + keeps the configuration it named. - `install-task` and `uninstall-task` are now `add-to-startup` and - `remove-from-startup`. The old names work until 1.0.0; `--delay` is gone. + `remove-from-startup`. The old names work until 1.0.0. + +### Removed + +- The 15-second delay after logon, and `--delay` with it: accepted and + ignored until 1.0.0. ### Fixed -- Office's updates no longer stop the watcher. They ended whatever a - scheduled task had started, the watcher included. - `purge` removes its folders even when they are marked read-only, as a folder copied back from a OneDrive backup is. @@ -205,7 +217,8 @@ and when it stops, on Windows' own signal that a game is running. including the scheduled tasks a program that needs administrator rights requires, and a Windows power plan. -[Unreleased]: https://github.com/Geeooff/GameModeExecutor/compare/v0.4.0...HEAD +[Unreleased]: https://github.com/Geeooff/GameModeExecutor/compare/v0.5.0...HEAD +[0.5.0]: https://github.com/Geeooff/GameModeExecutor/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/Geeooff/GameModeExecutor/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/Geeooff/GameModeExecutor/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/Geeooff/GameModeExecutor/compare/v0.1.0...v0.2.0 diff --git a/Cargo.lock b/Cargo.lock index 74b5f37..84339fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,7 +192,7 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "game-mode-executor" -version = "0.4.0" +version = "0.5.0" dependencies = [ "anyhow", "clap", diff --git a/Cargo.toml b/Cargo.toml index a95b4b9..9962a0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "game-mode-executor" -version = "0.4.0" +version = "0.5.0" authors = ["Geoffrey Vancoetsem"] edition = "2024" # Let chains, stable since 1.88. @@ -78,6 +78,9 @@ windows = { version = "0.62", features = [ # reads, without what PDH keeps for the process's life (Lot 16). "Win32_System_Performance", "Win32_System_SystemInformation", + # ITaskService: the configuration an earlier version's logon task + # passed, read before `add-to-startup` removes that task (Lot 19). + "Win32_System_TaskScheduler", "Win32_System_Threading", "Win32_System_WinRT", ] } diff --git a/docs/design/13-updating.md b/docs/design/13-updating.md index ca564ee..b21723e 100644 --- a/docs/design/13-updating.md +++ b/docs/design/13-updating.md @@ -68,6 +68,11 @@ dictates anyway and it would exist for symmetry alone. The cost of that freedom is a rule, in `AGENTS.md`: a change to any of those commands is verified on all three paths. +*Since [Lot 19](19-startup-list.md), in 0.5.0: `add-to-startup` and +`remove-from-startup` in place of `install-task` and `uninstall-task`, the +watcher started through Explorer rather than its task, and the failure path +runs `add-to-startup` rather than `schtasks /Run`. Noted 2026-11-16.* + ## What the release answers, measured 2026-09-18 against `v0.1.0` | Request | Answer | diff --git a/docs/design/19-startup-list.md b/docs/design/19-startup-list.md index a73802a..0421fd8 100644 --- a/docs/design/19-startup-list.md +++ b/docs/design/19-startup-list.md @@ -10,9 +10,11 @@ reason: Office's updates end what a logon task started, and spare what the - [x] `startup`: the `Run` value written and removed, the watcher started through Explorer, `task` reduced to removing a 0.4 task — 2026-11-16 - [x] `add-to-startup` and `remove-from-startup`, the old names as hidden aliases; the package, the zip's updater and `purge` on them — 2026-11-16 - [x] The user pages, the reference, the changelog — 2026-11-16 -- [x] Explorer starts the watcher from a person's terminal and from the package's action — 2026-11-16, below; from the zip's shell at the 0.5.0 update +- [x] Explorer starts the watcher from a person's terminal and from the package's action — 2026-11-16, below +- [ ] Explorer starts it from the zip's shell, at the 0.5.0 update - [x] The 0.4 task removed by `add-to-startup`; `uninstall-task` works as an alias — 2026-11-16, below -- [ ] An upgrade from the published 0.4.0, by the package and by the zip +- [x] An upgrade from the published 0.4.0 by the package, a configuration path of the task's kept — 2026-11-16, below +- [ ] An upgrade from the published 0.4.0 by the zip, at the 0.5.0 update - [x] The switch: off, then a logon; on again — 2026-11-16, below - [x] `remove-from-startup` takes the switch's entry too; `purge` lists the entry and no task — 2026-11-16, below - [ ] `purge` carried out, at the next full purge @@ -103,8 +105,10 @@ Two edge cases, neither leaving the program unstartable: shell's `schtasks /Run` finds no task. The old version's uninstall would not know the value; the next upgrade cleans it. - **A 0.4 zip copy whose update fails** puts its old executables back and - registers the task again beside the value: two starts at logon, and the - single-instance mutex ends the second. + runs its own `install-task`, its task intact. *A second case stood here, + the task registered again beside the value; it cannot happen: 0.4's shell + falls back only when unpacking or copying threw, before the new binary + ran. Corrected 2026-11-16, from the review below.* The verbs: `install-task` names something it would no longer do. A new name, with `install-task` and `uninstall-task` kept as aliases for the @@ -156,11 +160,59 @@ The maintainer took the lot and the recommendation, and named the verbs. - **The migration lives in the commands.** `add-to-startup` removes the 0.4 task after writing the value; `remove-from-startup` and `purge` remove one left over. That removal stays past 1.0.0: it protects a copy - that skips versions. + that skips versions. Before it goes, the task's `--config` is read, + through Task Scheduler's interface, and becomes the value's, so a path + chosen with 0.4's `install-task` survives the upgrade, as + [Lot 8](08-distribution.md) promised (added after the review below). - **No `Registry` row**: the program stays the one writer of the value. +- **Failing over the 0.4 task is a `warn`**, in `add-to-startup` and in + `remove-from-startup` alike: neither an install nor an uninstall rolls + back for it. - **A failure to start the watcher now is a `warn`**, not an error: the install goes on, and the next logon starts it. +## Reviewed before 0.5.0, 2026-11-16 + +A second agent, asked to argue against the release, read the branch +against `AGENTS.md`. Taken: + +- **The configuration a 0.4 task named was lost on upgrade**: the value + took the default path. Now read from the task, as above. +- **The `SAFETY` comment of the Explorer call was untrue**: a failure keeps + the failing object's error information, which was read and released + after `CoUninitialize`. The error is now text before COM is let go. +- **A kept entry was started unchecked.** One naming a missing file would + have had Explorer show a dialog; it is now said at `warn` and not + started. One naming another copy is said, and started, since Windows + starts that one at logon. +- **The switch was described as stronger than it is**: an install or an + update starts the watcher once even when it is off. Said so in the + module and the reference. +- **`remove()`** missed an empty value and a switch left without its + value, and the switch's removal was at `debug`; one `info` line now says + what went. `install-task --delay` exits 2 no more: accepted and ignored + until 1.0.0, as `run --hidden` is. +- The changelog claimed a fix not yet seen on the watcher itself; it now + says what was measured. The test scratch folder asserts it stays under + the temporary directory before emptying it. *How it works* had the + watcher at about 2 MB, a figure taken at start; the 2.7 MB of + [Lot 16](16-footprint.md) after twenty minutes is beside it now. + +Not taken: running 0.4's zip shell by hand before the tag. The shell is +0.4's, unchanged, and passes `install-task` alone, which a test pins; the +0.5.0 update will exercise it for real, as 0.4.0's did in +[Lot 17](17-log-rotation.md). + +Risks named, not measured: + +- A hung Explorer would hold the package's deferred action, since a + cross-process call has no timeout. +- A rollback after `AddToStartup` finds the new watcher holding its + executable, so the old file comes back at the next restart. 0.4's start + through the task had the same exposure. +- Without Explorer, asking for the shell's window list starts its + registered server before it fails. + ## Measured in the field, 2026-11-16 On the maintainer's machine, with the branch's release build (`54802623`), @@ -186,6 +238,16 @@ page: logon, no watcher. Turned on at 15:48: `00` and zeros, and at the next logon the watcher started 7 s after Explorer, its child. The value itself never changed: the switch is Windows' alone, as the module keeps it. +- **An upgrade from the published 0.4.0**, after the review, with the + 0.5.0 package built from the release commit (`5ddf2313`). The published + 0.4.0 installed at 16:29:03 registered its task and started its watcher; + `install-task --force --config` pointed the task at a copy of the + configuration, `config-test.toml`. The 0.5.0 package at 16:29:24: 0.4.0's + `stop --handover`, no `UnregisterTask`, *Configuration kept*, the task's + configuration read (*… names this configuration, so the startup entry + takes it*), the value written with `config-test.toml`, the task removed, + *Watcher started through Explorer*, 0.5.0 starting, its parent + `explorer.exe`. `add-to-startup --force` then put the default path back. - **Removal**, from the maintainer's terminal at 15:51: `remove-from-startup` removed the value and the switch's entry, which was then gone; `add-to-startup` put the value back. `purge`, answered no, listed *remove diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 2beda96..d3cedcb 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -61,7 +61,7 @@ Measured on a gaming PC in September 2026, private memory (Task Manager's | When | Processor | Memory | | --- | --- | --- | -| Waiting for a game | 0.03 % of one core | about 2 MB | +| Waiting for a game | 0.03 % of one core | about 2 MB at start, 2.7 MB after twenty minutes *(the second figure added 2026-11-16)* | | During a game | nothing measurable | unchanged | | Naming a game from the graphics card | | 0.25 MB, once | | The menu, first opened | | about 1 MB, once | diff --git a/docs/reference.md b/docs/reference.md index 3707f62..0d37e88 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -21,7 +21,7 @@ for the reasons, the [design record](design/). | `trigger start\|stop` | Run one event's commands now, to test them. | | `validate` | Check the configuration; exits 3 or 4 on a problem. | | `init [--force]` | Write the starter configuration to `%APPDATA%\GameModeExecutor`; an existing one is kept unless `--force`. | -| `add-to-startup [--force]` | Add `gamemode-executorw.exe` to the programs Windows starts at logon, remove the logon task of a version up to 0.4, and have Explorer start the watcher. An existing entry is kept unless `--force`. | +| `add-to-startup [--force]` | Add `gamemode-executorw.exe` to the programs Windows starts at logon, with the configuration the logon task of a version up to 0.4 named if there was one, remove that task, and have Explorer start the watcher. An existing entry is kept unless `--force`. | | `remove-from-startup` | Remove that entry, its switch in Settings, and the logon task of a version up to 0.4. | | `update [--check]` | Look for a newer release on GitHub; without `--check`, download, verify against `SHA256SUMS.txt` and install it. The only command that connects to anything. | | `stop [--handover]` | Stop the running watcher as *Quit* does, and wait for it to go. With `--handover`, an open game session is left to the next watcher, nothing run. | @@ -35,7 +35,7 @@ else `%APPDATA%\GameModeExecutor\config.toml`. The setup commands (`init`, `add-to-startup`, `remove-from-startup`, `stop`) log what they did under `setup`, `update` under `update`. `install-task` and `uninstall-task`, the old names of the startup commands, still work until -1.0.0; `--delay` went with the task. +1.0.0, and `--delay` is accepted and ignored until then. ## Configuration @@ -169,7 +169,7 @@ the file at once; lines never interleave, since each is one append. | Log | `%LOCALAPPDATA%\GameModeExecutor\logs\` | disposable | | Session marker | `%LOCALAPPDATA%\GameModeExecutor\pending-stop-actions` | a game session not yet closed. `state = open` while a watcher holds it, `left` once one stopped and left it to the next start; `open` found at a start means that watcher ended without stopping. | | Fault marker | `%LOCALAPPDATA%\GameModeExecutor\configuration-fault` | the configuration was unusable when last read, so the next usable read says the fault is over | -| Startup entry | `GameModeExecutor` under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` | the watcher's and the configuration's absolute paths; removed on uninstall, kept on upgrade. Its switch in Settings is Windows': turned off, it stays off. | +| Startup entry | `GameModeExecutor` under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` | the watcher's and the configuration's absolute paths; removed on uninstall, kept on upgrade. Its switch in Settings is Windows': turned off, the watcher no longer starts at logon, though an install or an update still starts it once. | | Updates | `%LOCALAPPDATA%\GameModeExecutor\updates\` | a release being installed; emptied at the next start, the installer's log kept if the update failed | ## Building and releasing diff --git a/src/cli.rs b/src/cli.rs index f7487e4..9ace72a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -55,9 +55,10 @@ pub enum Command { /// For an unattended instance use `gamemode-executorw.exe`, which is the /// same watcher with no console at all. `add-to-startup` adds that one. Run { - /// Accepted and ignored. A task registered before this binary had a - /// windowless twin still passes it, and refusing it would stop that - /// task dead at the next logon. + /// Accepted and ignored. A logon task registered before this binary + /// had a windowless twin still passes it, until `add-to-startup` + /// removes that task, and refusing it would stop the task dead at the + /// next logon. #[arg(long, hide = true)] hidden: bool, }, @@ -96,6 +97,10 @@ pub enum Command { /// Replace an entry that is already there. #[arg(long)] force: bool, + /// Accepted and ignored until 1.0.0, with the old name: the logon + /// task's delay, which went with the task. + #[arg(long, hide = true)] + delay: Option, }, /// Remove the watcher from the programs Windows starts at logon. #[command(alias = "uninstall-task")] @@ -157,16 +162,23 @@ pub fn run(cli: Cli, console: bool) -> Result<()> { config::write_starter(&path, force)?; return Ok(()); } - Some(Command::AddToStartup { force }) => { + Some(Command::AddToStartup { force, .. }) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; - let path = resolve_config_path(cli.config)?; + // A path given now wins; then the one an earlier version's logon + // task passed, so an upgrade keeps it; then the default. + let path = match cli.config { + Some(path) => path, + None => match task::configuration() { + Some(path) => path, + None => resolve_config_path(None)?, + }, + }; startup::add(&path, force)?; return Ok(()); } Some(Command::RemoveFromStartup) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; - startup::remove()?; - return task::remove_leftover(); + return startup::remove(); } Some(Command::Stop { handover }) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; @@ -637,7 +649,7 @@ mod tests { )); assert!(matches!( parse(&["add-to-startup", "--force"]).command, - Some(Command::AddToStartup { force: true }) + Some(Command::AddToStartup { force: true, .. }) )); assert!(matches!( parse(&["remove-from-startup"]).command, @@ -660,7 +672,11 @@ mod tests { fn the_old_names_of_the_startup_commands_still_work_unoffered() { assert!(matches!( parse(&["install-task"]).command, - Some(Command::AddToStartup { force: false }) + Some(Command::AddToStartup { force: false, .. }) + )); + assert!(matches!( + parse(&["install-task", "--delay", "1m", "--force"]).command, + Some(Command::AddToStartup { force: true, .. }) )); assert!(matches!( parse(&["uninstall-task"]).command, diff --git a/src/purge.rs b/src/purge.rs index 35a7a7f..0dc4557 100644 --- a/src/purge.rs +++ b/src/purge.rs @@ -270,7 +270,7 @@ pub fn discover(config: Option<&config::Config>, config_path: &Path) -> Layout { let log_dir = config.map_or_else(config::default_log_dir, |config| config.general.log_dir()); Layout { watcher_running: win::SingleInstance::is_held(service::INSTANCE), - startup_entry: startup::entry().is_some(), + startup_entry: startup::exists(), task_registered: task::exists(), config_candidates: candidates, log_dir, diff --git a/src/startup.rs b/src/startup.rs index 9bdb07f..7875a94 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -11,10 +11,14 @@ //! //! - The program is the one writer of its value, for the package and the zip //! alike, and a value already there is kept unless asked: it may name a -//! configuration the user chose. +//! configuration the user chose. A kept value is checked before it is +//! started: one naming a missing file is not handed to Explorer, which +//! would answer with a dialog, and one naming another copy is said. //! - The switch is Explorer's. Its entry under `StartupApproved\Run` is never -//! written here, so a watcher switched off stays off across upgrades, and it -//! is removed with the value, by name, so nothing of ours is left behind. +//! written here, so a watcher switched off is still not started at logon +//! after an upgrade -- an install or an update starts it once all the same, +//! since reading the switch is undocumented. The entry is removed with the +//! value, by name, so nothing of ours is left behind. //! - The watcher started right after an install is started by Explorer, //! through the shell's automation object on the desktop, so it gets the //! parent a logon gives it: the one the measurement saw survive. A process @@ -82,7 +86,7 @@ pub fn registration(exists: bool, force: bool) -> Registration { } } -/// The entry as it stands, if there is one. +/// The entry's command line, if there is one worth the name. pub fn entry() -> Option { CURRENT_USER .open(RUN_KEY) @@ -92,6 +96,17 @@ pub fn entry() -> Option { .filter(|line| !line.is_empty()) } +/// Whether anything of ours is under either key: the value, of whatever +/// type or length, or the switch Explorer wrote for it. +pub fn exists() -> bool { + let under = |path: &str| { + CURRENT_USER + .open(path) + .is_ok_and(|key| key.get_type(VALUE_NAME).is_ok()) + }; + under(RUN_KEY) || under(APPROVED_KEY) +} + /// Add the watcher to the programs Windows starts at logon, unless it is /// there already, then have Explorer start it, so the icon appears now /// rather than at the next logon. A watcher already running keeps the @@ -101,6 +116,8 @@ pub fn entry() -> Option { /// updater after every update. Every outcome is logged at `info`, under /// `setup`. pub fn add(config_path: &Path, force: bool) -> Result { + let here = std::env::current_exe().context("cannot locate the running executable")?; + let twin = here.with_file_name(WATCHER_EXE); let existing = entry(); let outcome = registration(existing.is_some(), force); let line = match (existing, outcome) { @@ -114,16 +131,14 @@ pub fn add(config_path: &Path, force: bool) -> Result { line } _ => { - let here = std::env::current_exe().context("cannot locate the running executable")?; - let exe = here.with_file_name(WATCHER_EXE); - if !exe.exists() { + if !twin.exists() { bail!( "`{}` is missing. It is built alongside this program and is the one Windows \ starts at logon, because it has no console to leave on screen.", - exe.display() + twin.display() ); } - let line = command_line(&exe, &absolute(config_path)?)?; + let line = command_line(&twin, &absolute(config_path)?)?; CURRENT_USER .create(RUN_KEY) .and_then(|key| key.set_string(VALUE_NAME, &line)) @@ -146,53 +161,85 @@ pub fn add(config_path: &Path, force: bool) -> Result { line } }; - // A task left by 0.4 would start a second watcher at logon, and that one - // first: worth a word, not worth failing an install over. - if let Err(error) = crate::task::remove_leftover() { + remove_leftover_task(); + let (program, _) = split(&line); + if !Path::new(program).is_file() { tracing::warn!( target: target::SETUP, - task = crate::task::TASK_NAME, - error = %format!("{error:#}"), - "The logon task of an earlier version could not be removed, so it may start a second watcher at logon" + program, + "The startup entry names a program that is not there, so nothing is started; --force replaces the entry" ); + } else { + if !same_file(Path::new(program), &twin) { + tracing::warn!( + target: target::SETUP, + program, + this_copy = %twin.display(), + "The startup entry names another copy of the program, which is the one started; --force replaces the entry" + ); + } + start(&line); } - start(&line); Ok(outcome) } /// Remove the watcher from the programs Windows starts at logon, and the /// Startup page's switch for it. An entry that is not there is not an error. pub fn remove() -> Result<()> { - if entry().is_some() { - CURRENT_USER - .create(RUN_KEY) - .and_then(|key| key.remove_value(VALUE_NAME)) - .with_context(|| format!("cannot remove `{VALUE_NAME}` from HKCU\\{RUN_KEY}"))?; - tracing::info!( + let had_value = remove_from(RUN_KEY)?; + let had_switch = remove_from(APPROVED_KEY)?; + match (had_value, had_switch) { + (true, _) => tracing::info!( target: target::SETUP, value = VALUE_NAME, + switch = had_switch, "Removed from the programs Windows starts at logon" - ); - } else { - tracing::info!( + ), + (false, true) => tracing::info!( + target: target::SETUP, + value = VALUE_NAME, + "No startup entry to remove; the switch Settings kept for it is removed" + ), + (false, false) => tracing::info!( target: target::SETUP, value = VALUE_NAME, "No startup entry to remove" - ); + ), + } + remove_leftover_task(); + Ok(()) +} + +/// Delete our value under `path`, saying whether it was there. +fn remove_from(path: &str) -> Result { + let Ok(key) = CURRENT_USER.options().read().write().open(path) else { + return Ok(false); + }; + if key.get_type(VALUE_NAME).is_err() { + return Ok(false); } - // Explorer writes the switch's entry when it first lists ours. - if let Ok(key) = CURRENT_USER.options().read().write().open(APPROVED_KEY) - && key.get_type(VALUE_NAME).is_ok() - { - key.remove_value(VALUE_NAME) - .with_context(|| format!("cannot remove `{VALUE_NAME}` from HKCU\\{APPROVED_KEY}"))?; - tracing::debug!( + key.remove_value(VALUE_NAME) + .with_context(|| format!("cannot remove `{VALUE_NAME}` from HKCU\\{path}"))?; + Ok(true) +} + +/// A task left by 0.4 would start a second watcher at logon, and that one +/// first: worth a word, never worth failing an install or an uninstall over. +fn remove_leftover_task() { + if let Err(error) = crate::task::remove_leftover() { + tracing::warn!( target: target::SETUP, - value = VALUE_NAME, - "The Startup page's switch for it removed" + task = crate::task::TASK_NAME, + error = %format!("{error:#}"), + "The logon task of an earlier version could not be removed, so it may start a second watcher at logon" ); } - Ok(()) +} + +/// Whether two paths name the same file, compared as Windows compares +/// them: without regard to case. +fn same_file(a: &Path, b: &Path) -> bool { + a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase() } /// The value's data: the twin and the configuration it reads, both quoted. @@ -250,7 +297,11 @@ fn start(line: &str) { /// starts is Explorer's child. Microsoft's documented interfaces, in the /// order Raymond Chen gives them: the desktop's view found as in his post of /// 2013-03-18, its automation object asked as in the one linked above. -fn start_from_explorer(program: &str, parameters: &str) -> windows::core::Result<()> { +/// +/// A failure comes back as text, read while COM is still initialised: the +/// error holds the failing object's error information, which must not be +/// read or released after `CoUninitialize`. +fn start_from_explorer(program: &str, parameters: &str) -> std::result::Result<(), String> { // SAFETY: no pointers; paired with the uninitialise below, on this thread. let com = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) }; let directory = Path::new(program) @@ -258,9 +309,10 @@ fn start_from_explorer(program: &str, parameters: &str) -> windows::core::Result .map(|dir| dir.display().to_string()) .unwrap_or_default(); // SAFETY: every interface is a COM pointer the call before handed out and - // windows-rs releases on drop, all of them inside this block, before COM - // is uninitialised; the VARIANTs and the BSTR outlive the calls they are - // passed to, which copy what they keep. + // windows-rs releases on drop, all of them inside the closure; an error + // is turned into text before the closure's result leaves this statement, + // so nothing of COM outlives it. The VARIANTs and the BSTR outlive the + // calls they are passed to, which copy what they keep. let started = unsafe { (|| -> windows::core::Result<()> { let windows: IShellWindows = @@ -292,10 +344,19 @@ fn start_from_explorer(program: &str, parameters: &str) -> windows::core::Result &VARIANT::from(SW_SHOWNORMAL.0), ) })() - }; + } + .map_err(|error| { + // The desktop's window not found comes back as a success code + // with no object, whose message would read as a success. + if error.code().is_ok() { + "Explorer's desktop is not there to ask".to_owned() + } else { + error.to_string() + } + }); if com.is_ok() { // SAFETY: COM was initialised above on this thread, and every - // interface obtained under it has been released. + // interface and error information obtained under it is released. unsafe { CoUninitialize() }; } started @@ -370,6 +431,24 @@ mod tests { assert_eq!(split(r"C:\w.exe"), (r"C:\w.exe", "")); } + /// The entry and this copy's path come from different writers, which + /// may not agree on case. + #[test] + fn the_same_file_is_recognised_whatever_the_case() { + assert!(same_file( + Path::new( + r"C:\Users\Me\AppData\Local\Programs\GameModeExecutor\gamemode-executorw.exe" + ), + Path::new( + r"c:\users\me\appdata\local\programs\GameModeExecutor\GAMEMODE-EXECUTORW.EXE" + ) + )); + assert!(!same_file( + Path::new(r"C:\Tools\GME\gamemode-executorw.exe"), + Path::new(r"C:\Programs\GME\gamemode-executorw.exe") + )); + } + /// A relative path would resolve at logon against Explorer's working /// directory, and the watcher would exit 3 with nobody watching. #[test] diff --git a/src/task.rs b/src/task.rs index 476bfc4..a099d23 100644 --- a/src/task.rs +++ b/src/task.rs @@ -6,10 +6,24 @@ //! end -- so `add-to-startup`, `remove-from-startup` and `purge` remove it. //! Kept past 1.0.0, unlike the old verbs, decided 2026-11-16: it is what //! protects a copy that skips versions. +//! +//! Before it goes, `add-to-startup` reads which configuration the task +//! passed, so a path chosen with 0.4's `install-task --config` survives the +//! upgrade, as Lot 8 promised. Read through Task Scheduler's own interface, +//! which answers in UTF-16: `schtasks /Query /XML` writes through the +//! console's code page, and a user name with an accent would not survive it. +use std::path::PathBuf; use std::process::Command; use anyhow::{Context, Result, bail}; +use windows::Win32::System::Com::{ + CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, + CoUninitialize, +}; +use windows::Win32::System::TaskScheduler::{IExecAction, ITaskService, TaskScheduler}; +use windows::Win32::System::Variant::VARIANT; +use windows::core::{BSTR, Interface}; /// The task an earlier version registered, folder included. The folder is /// left in place when the task goes: the elevated tasks a recipe asks for @@ -25,6 +39,81 @@ pub fn exists() -> bool { .unwrap_or(false) } +/// The configuration that task passes the watcher, if the task is there and +/// passes one. Anything that cannot be read is `None`: the caller then uses +/// the default, as it would without a task. +pub fn configuration() -> Option { + // SAFETY: no pointers; paired with the uninitialise below, on this thread. + let com = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + // SAFETY: every interface is a COM pointer the call before handed out and + // windows-rs releases on drop, inside the closure; the result is plain + // text by the time it leaves this statement, so nothing of COM outlives + // it. The BSTRs and VARIANTs outlive the calls that read them. + let arguments = unsafe { + (|| -> windows::core::Result { + let service: ITaskService = + CoCreateInstance(&TaskScheduler, None, CLSCTX_INPROC_SERVER)?; + let none = VARIANT::default(); + service.Connect(&none, &none, &none, &none)?; + let (folder, name) = TASK_NAME.rsplit_once('\\').unwrap_or(("", TASK_NAME)); + let task = service + .GetFolder(&BSTR::from(format!("\\{folder}")))? + .GetTask(&BSTR::from(name))?; + // Task Scheduler counts actions from one. + let action: IExecAction = task.Definition()?.Actions()?.get_Item(1)?.cast()?; + let mut arguments = BSTR::new(); + action.Arguments(&mut arguments)?; + Ok(arguments.to_string()) + })() + } + .ok(); + if com.is_ok() { + // SAFETY: COM was initialised above on this thread, and every + // interface obtained under it is released. + unsafe { CoUninitialize() }; + } + let path = config_argument(&arguments?)?; + tracing::debug!( + target: crate::logging::target::SETUP, + task = TASK_NAME, + config = %path.display(), + "The logon task of an earlier version names this configuration, so the startup entry takes it" + ); + Some(path) +} + +/// The path after `--config` (or `-c`, or `--config=`) in a command line's +/// arguments, quoted or not, the way the watcher's own parser reads it. +fn config_argument(arguments: &str) -> Option { + let mut rest = arguments.trim_start(); + while !rest.is_empty() { + let (token, after) = next_token(rest); + if token == "--config" || token == "-c" { + let (value, _) = next_token(after.trim_start()); + return (!value.is_empty()).then(|| PathBuf::from(value)); + } + if let Some(value) = token.strip_prefix("--config=") { + return (!value.is_empty()).then(|| PathBuf::from(value)); + } + rest = after.trim_start(); + } + None +} + +/// One argument, its quotes taken off, and what follows it. +fn next_token(text: &str) -> (String, &str) { + let mut token = String::new(); + let mut quoted = false; + for (index, character) in text.char_indices() { + match character { + '"' => quoted = !quoted, + c if c.is_whitespace() && !quoted => return (token, &text[index..]), + c => token.push(c), + } + } + (token, "") +} + /// Remove that task if it is there, saying so at `info`; nothing to say /// when it is not. pub fn remove_leftover() -> Result<()> { @@ -59,3 +148,44 @@ fn schtasks(args: &[&str]) -> Command { command.args(args).creation_flags(CREATE_NO_WINDOW); command } + +#[cfg(test)] +mod tests { + use super::*; + + /// What 0.4's `install-task` wrote, and what a person may have typed. + #[test] + fn the_configuration_is_read_from_the_tasks_arguments() { + let read = + |arguments: &str| config_argument(arguments).map(|path| path.display().to_string()); + assert_eq!( + read(r#"--config "C:\Users\Rémi\AppData\Roaming\GameModeExecutor\config.toml""#) + .as_deref(), + Some(r"C:\Users\Rémi\AppData\Roaming\GameModeExecutor\config.toml") + ); + assert_eq!( + read(r"--config C:\x\config.toml").as_deref(), + Some(r"C:\x\config.toml") + ); + assert_eq!( + read(r#"-c "C:\A B\c.toml""#).as_deref(), + Some(r"C:\A B\c.toml") + ); + assert_eq!( + read(r#"--config="C:\A B\c.toml""#).as_deref(), + Some(r"C:\A B\c.toml") + ); + assert_eq!( + read(r#"run --hidden --config "C:\c.toml""#).as_deref(), + Some(r"C:\c.toml") + ); + } + + #[test] + fn no_configuration_in_the_arguments_is_none() { + assert_eq!(config_argument(""), None); + assert_eq!(config_argument("--hidden"), None); + assert_eq!(config_argument("--config"), None); + assert_eq!(config_argument(r#"--config """#), None); + } +} diff --git a/src/testing.rs b/src/testing.rs index a05ce74..536ab33 100644 --- a/src/testing.rs +++ b/src/testing.rs @@ -7,11 +7,21 @@ use std::sync::atomic::{AtomicU32, Ordering}; /// /// Emptied first: the name carries the test process's id, which Windows /// reuses, and a folder an earlier run left under the same id once handed a -/// scenario that run's session marker (2026-10-17). +/// scenario that run's session marker (2026-10-17). Before anything is +/// removed, the folder is checked to be a direct child of the temporary +/// directory: `join` discards what comes before an absolute path, so a +/// prefix that were one would point the removal elsewhere. pub fn fresh_dir(prefix: &str) -> PathBuf { static COUNTER: AtomicU32 = AtomicU32::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!("{prefix}-{}-{n}", std::process::id())); + let temp = std::env::temp_dir(); + let dir = temp.join(format!("{prefix}-{}-{n}", std::process::id())); + assert_eq!( + dir.parent(), + Some(temp.as_path()), + "a scratch folder outside the temporary directory: {}", + dir.display() + ); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir