diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 0270bb1..2fb3386 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -67,8 +67,8 @@ "problemMatcher": ["$rustc"] }, { - "label": "Watcher: restart the logon task", - "detail": "stop it, wait for the process to actually go, start it again", + "label": "Watcher: restart the installed one", + "detail": "hand a game session over, then have Explorer start it again from its startup entry", "type": "shell", "command": "pwsh", "args": [ @@ -76,7 +76,7 @@ "-ExecutionPolicy", "Bypass", "-Command", - "Stop-ScheduledTask -TaskPath '\\GameModeExecutor\\' -TaskName Watcher; $d=(Get-Date).AddSeconds(20); while((Get-Date) -lt $d -and @(Get-Process gamemode-executorw -ErrorAction Ignore).Count){Start-Sleep -Milliseconds 250}; Start-ScheduledTask -TaskPath '\\GameModeExecutor\\' -TaskName Watcher; Start-Sleep 2; Get-Process gamemode-executorw -ErrorAction Ignore | Select-Object Id, StartTime" + "$gme = \"$env:LOCALAPPDATA\\Programs\\GameModeExecutor\\gamemode-executor.exe\"; & $gme stop --handover; & $gme add-to-startup; Start-Sleep 2; Get-Process gamemode-executorw -ErrorAction Ignore | Select-Object Id, StartTime" ], "problemMatcher": [] }, @@ -90,7 +90,7 @@ "-ExecutionPolicy", "Bypass", "-Command", - "Get-Content -Wait -Tail 30 \"$env:LOCALAPPDATA\\GameModeExecutor\\logs\\gamemode-executor.log\"" + "Get-ChildItem \"$env:LOCALAPPDATA\\GameModeExecutor\\logs\\gamemode-executor.*.log\" | Sort-Object LastWriteTime | Select-Object -Last 1 | Get-Content -Wait -Tail 30" ], "isBackground": true, "problemMatcher": [] diff --git a/AGENTS.md b/AGENTS.md index 61b5e6f..b212386 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,7 @@ This file says how to work here. The *why* is in the rules — the engine's session, `update`'s phase, the supervisor's verdict — what to draw and what a click means. - **The setup commands are a contract with three callers.** `stop`, `init`, - `install-task` and `uninstall-task` are sequenced by the package + `add-to-startup` and `remove-from-startup` are sequenced by the package (`scripts/msi.ps1`), by the zip's after-exit shell in `update`, and by `purge`. A change to any of them is verified on all three paths. - Module doc comments carry the rules a module is shaped by: read them @@ -138,7 +138,7 @@ This file says how to work here. The *why* is in user's commands: `cargo test -- --ignored a_real_activation_drives_a_session`. - **Verify as the user runs it:** `gamemode-executor stop`, copy the two release executables over the installed ones, `gamemode-executor - install-task`, and read the log at `debug` through a real game. A package + add-to-startup`, and read the log at `debug` through a real game. A package change: uninstall from *Programs and Features*, install the new `dist\` package — the product code is fixed per version. Never restart the watcher while a game runs: that fires the stop commands. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7feb10f..5150af0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,9 +20,20 @@ a section is written. - Each release file comes with GitHub's attestation that the release workflow built it from the tagged commit: `gh attestation verify --repo Geeooff/GameModeExecutor`. +- The watcher appears in Settings, *Apps → Startup*, as *GameModeExecutor + watcher*, with a switch to stop it starting at logon. + +### Changed + +- Windows starts the watcher at logon from your `Run` key instead of a + scheduled task; an upgrade removes the old task. +- `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. ### 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. diff --git a/Cargo.toml b/Cargo.toml index 3104247..a95b4b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,10 @@ windows = { version = "0.62", features = [ # CoInitializeEx: the apartment Microsoft asks for before ShellExecuteEx, # in the helper that opens what the menu offers. "Win32_System_Com", + # IShellBrowser and IShellView, and the VARIANTs IShellDispatch2 takes: + # `add-to-startup` asks Explorer to start the watcher (Lot 19). + "Win32_System_Ole", + "Win32_System_Variant", # The updater: WinHTTP for the release, CNG for the SHA-256 of what it # fetched. Microsoft's libraries, no HTTP or hashing crate. "Win32_Networking_WinHttp", diff --git a/docs/design/19-startup-list.md b/docs/design/19-startup-list.md index 1c9a703..a73802a 100644 --- a/docs/design/19-startup-list.md +++ b/docs/design/19-startup-list.md @@ -1,11 +1,23 @@ # Lot 19 — Starting from Windows' Startup list -**Status: spike done 2026-11-16; proposed for a decision.** The maintainer +**Status: decided 2026-11-16, being built; ships in 0.5.0.** The maintainer wants GameModeExecutor in *Settings → Apps → Startup*, with its switch, instead of a logon task that page does not show. The spike adds a second reason: Office's updates end what a logon task started, and spare what the `Run` key started. +- [x] Spike: survival, what a `Run` entry gives, the cost per caller — 2026-11-16, below +- [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] 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] 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 +- [ ] The watcher outlives an Office update + ## Why - **Transparency.** The Startup page, and Task Manager's, list three sources: @@ -79,7 +91,9 @@ The setup commands' three callers each meet the change | The zip's after-exit shell | calls the new binary's `install-task` | unchanged, so the verb must keep working: a 0.4 copy's shell calls it | | `update`, a failed install | `schtasks /Run` restarts the old watcher | a 0.4 copy's shell still does that; the new version's shell starts the watcher the new way | | `purge` | removes the task | removes the value, its `StartupApproved` entry, and a task left over | -| `status` | says whether the task is there | says whether the value is there and points at this copy | + +*A `status` row said `status` reported the task; it never did, and needs +nothing here. Corrected 2026-11-16.* Two edge cases, neither leaving the program unstartable: @@ -125,7 +139,59 @@ command must start it itself: **Recommended: 2**, measured on all three paths. It gives the parent that was measured rather than one that might hold. -## Done when, proposed +## Decided 2026-11-16 + +The maintainer took the lot and the recommendation, and named the verbs. + +- **`add-to-startup` and `remove-from-startup`**: *startup* as the page + says it, with a verb in plain English. `enable`/`disable` were turned + down: they are what the switch does, and the switch keeps the entry. +- **The old names live in the command line, not in the package.** Only a + 0.4 zip copy's updater calls `install-task` on the new binary; nothing + automatic calls `uninstall-task`, since the 0.4 package runs its own + executable and skips that action on an upgrade. So both are hidden + aliases, accepted until 1.0.0, and the package names only the new + actions, `AddToStartup` and `RemoveFromStartup`, in the old ones' places + and conditions. +- **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. +- **No `Registry` row**: the program stays the one writer of the value. +- **A failure to start the watcher now is a `warn`**, not an error: the + install goes on, and the next logon starts it. + +## Measured in the field, 2026-11-16 + +On the maintainer's machine, with the branch's release build (`54802623`), +from the log and the process list, the maintainer's eyes on the Settings +page: + +- **From a terminal**, a game session open. The installed copy stopped with + `--handover` and the executables replaced, then `add-to-startup` at + 15:40:22: the value written, *Logon task of an earlier version removed*, + *Watcher started through Explorer*. The new watcher's parent was + `explorer.exe`; it started 16 ms after the request and resumed the session. +- **From the package.** 0.4.0 uninstalled from Settings: its action ran + `uninstall-task` on the new executables, and the alias removed the value + at 15:43:08. The branch's package installed: *Configuration kept*, the + value added, *Watcher started through Explorer* at 15:43:27, from the + deferred action. The watcher's parent: `explorer.exe`. So Explorer takes + the request from Windows Installer's custom action, the case that was + least certain. +- **On the page**: *GameModeExecutor watcher — Geoffrey Vancoetsem*, the + green controller, *On*, *Not measured*. +- **The switch.** Turned off at 15:46: the running watcher went on, and + Explorer wrote `01` and a timestamp in `StartupApproved\Run`. At the next + 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. +- **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 + the startup entry `GameModeExecutor` and its switch* and no task. + +## Done when The watcher starts at logon from the `HKCU` `Run` key and shows on the Startup page with its switch; an install, an upgrade and a zip update each diff --git a/docs/design/README.md b/docs/design/README.md index a34d54b..d839e04 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -29,7 +29,7 @@ the pages keep the history. | 16 | [What the watcher keeps](16-footprint.md) | done 2026-09-23; memory at rest to measure again against 0.3.0 | | 17 | [A log that turns over each day](17-log-rotation.md) | done 2026-09-26; its last checks seen 2026-10-17 | | 18 | [When the game is gone and nobody is there](18-game-gone-nobody-there.md) | proposed, not decided | -| 19 | [Starting from Windows' Startup list](19-startup-list.md) | spike done: Office spares `Run` starts; proposed | +| 19 | [Starting from Windows' Startup list](19-startup-list.md) | being built, for 0.5.0; field checks open | | 20 | [The build chain, official and kept current](20-build-chain.md) | built 2026-10-17; the first wait and the first attested release to see | | 21 | [Moving to windows-rs 0.100](21-windows-rs-0100.md) | proposed; waiting for `windows` 0.100 | diff --git a/docs/getting-started.md b/docs/getting-started.md index 863b4c8..42d390d 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -16,7 +16,8 @@ Run one thing when a game starts, another when it stops. Five minutes. **The installer** (`.msi`) needs no administrator rights. It installs for you alone in `%LOCALAPPDATA%\Programs\GameModeExecutor`, writes a starter -configuration, registers the logon task and starts the watcher. Windows warns +configuration, adds the watcher to the programs Windows starts at logon and +starts it. Windows warns because it is not signed; the release page says how to check it came from this repository. A newer release installs over it and keeps your configuration. @@ -27,10 +28,10 @@ OneDrive. Then, once: ```bash gamemode-executor init -gamemode-executor install-task +gamemode-executor add-to-startup ``` -Moving the folder later means `install-task --force` again. +Moving the folder later means `add-to-startup --force` again. There are two executables. `gamemode-executorw.exe` is the watcher: no window, started at logon, never by you. `gamemode-executor.exe` is the one you type @@ -92,7 +93,8 @@ Not visible? Click the `^` next to the clock and drag it onto the taskbar. | **Quit** | stops the watcher, running the stop commands first | After *Quit*, it starts again at the next logon, or from **GameModeExecutor** -in the Start menu. +in the Start menu. Settings lists it under *Apps → Startup* as +*GameModeExecutor watcher*; its switch there stops it starting at logon. ## Updating @@ -164,9 +166,12 @@ running; a second one is refused. ## Turning it off +*Quit*, then turn *GameModeExecutor watcher* off in Settings, *Apps → +Startup*. Or, from a terminal: + ```bash gamemode-executor stop -gamemode-executor uninstall-task +gamemode-executor remove-from-startup ``` To remove it entirely: *Programs and Features*, or `purge` — see diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 9b13ee0..2beda96 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -75,8 +75,8 @@ processor in all. A Windows program is built either as a console program, which can print, or as a windowless one, which cannot. One file cannot be both. `gamemode-executor.exe` answers your commands in a terminal, and the shell -waits for its result. `gamemode-executorw.exe` runs the watcher from the logon -task and the installer's steps, with no window to flash; it writes to the log +waits for its result. `gamemode-executorw.exe` runs the watcher at logon and +the installer's steps, with no window to flash; it writes to the log instead. Python does the same with `python.exe` and `pythonw.exe`. A named lock allows one watcher at a time: a second one is refused, so the @@ -84,11 +84,14 @@ Start menu's **GameModeExecutor** is safe to click. ## What starts it -A per-user scheduled task, at logon, fifteen seconds in. Not a service: -services run in a separate session and cannot see the desktop the game is on. -The task is registered from XML, because the usual shortcut would leave a -72-hour execution limit and two battery conditions on it. The installer stops -the watcher before it replaces or removes the files. +Windows, at logon, from your `Run` key: Settings lists it under *Apps → +Startup* as *GameModeExecutor watcher*, with a switch to turn it off. Not a +service: services run in a separate session and cannot see the desktop the +game is on. The installer adds the entry, has Explorer start the watcher +right away, and stops it before it replaces or removes the files. + +*Up to 0.4 a scheduled task started it, and Office's updates ended what that +task started: measured in [Lot 19](design/19-startup-list.md).* The watcher owns one hidden window: the icon hangs off it, and it is how Windows tells the watcher the session is ending. @@ -142,7 +145,7 @@ for a hand-installed copy), checks its SHA-256 against the release's watcher with a handover, replaces the files and starts the new version. A zip copy is updated by a hidden shell that waits for the watcher to exit, unpacks the zip over the folder, keeping the old executables as `.old`, and -runs `install-task`. +runs `add-to-startup`. The hash proves the file is the one the release published; the program has no code signature ([why](design/13-updating.md)). Each release file also carries @@ -152,16 +155,17 @@ checks. ## Removing it -*Programs and Features* removes the executables and the logon task, and keeps -your configuration and log, as Windows applications do. +*Programs and Features* removes the executables and the startup entry, and +keeps your configuration and log, as Windows applications do. ``` gamemode-executor purge ``` -removes every trace after a `yes`: the task, the configuration, every log -file, the session marker, the updates folder, then the executables. It refuses -during a game, and leaves what it did not create, such as a recipe's tasks. +removes every trace after a `yes`: the startup entry, the configuration, +every log file, the session marker, the updates folder, then the executables. +It refuses during a game, and leaves what it did not create, such as a +recipe's tasks. ## What it does not do @@ -180,7 +184,8 @@ during a game, and leaves what it did not create, such as a recipe's tasks. | The program | `%LOCALAPPDATA%\Programs\GameModeExecutor`, or wherever you unzipped it | | Configuration | `config.toml` next to the executable if there is one, else `%APPDATA%\GameModeExecutor\config.toml` (roams with your profile) | | Log | `%LOCALAPPDATA%\GameModeExecutor\logs`, one file a day, seven kept; the day changes at midnight UTC | -| Scheduled tasks | the `GameModeExecutor` folder in Task Scheduler | +| Startup entry | `GameModeExecutor` under `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`; its switch in Settings, *Apps → Startup* | +| A recipe's scheduled tasks | the `GameModeExecutor` folder in Task Scheduler | The [design record](design/) has the measurements behind all this, starting with [Detection](design/00-detection.md); the [reference](reference.md) has diff --git a/docs/recipes/fancontrol-fan-profiles/config.toml b/docs/recipes/fancontrol-fan-profiles/config.toml index 484172e..cbf0aea 100644 --- a/docs/recipes/fancontrol-fan-profiles/config.toml +++ b/docs/recipes/fancontrol-fan-profiles/config.toml @@ -13,8 +13,8 @@ # chosen when the tasks are registered and lives in the task, so this file is # the same for everyone and never has to know what you called yours. # -# The backslash is a Task Scheduler folder, not a path on disk: everything this -# program installs lives under \GameModeExecutor rather than loose at the root. +# The backslash is a Task Scheduler folder, not a path on disk: the recipe's +# tasks live under \GameModeExecutor rather than loose at the root. # Note the single quotes -- TOML takes those literally, so the backslash needs # no doubling. # diff --git a/docs/recipes/fancontrol-fan-profiles/uninstall-tasks.ps1 b/docs/recipes/fancontrol-fan-profiles/uninstall-tasks.ps1 index 044571c..eacfb62 100644 --- a/docs/recipes/fancontrol-fan-profiles/uninstall-tasks.ps1 +++ b/docs/recipes/fancontrol-fan-profiles/uninstall-tasks.ps1 @@ -10,8 +10,8 @@ # \GameModeExecutor\FanControl Game # # What stays: FanControl and its configurations, the \GameModeExecutor folder -# in Task Scheduler and every other task in it -- the watcher's own logon task -# lives there -- and GameModeExecutor's config.toml, which still names the two +# in Task Scheduler and every other task in it, and GameModeExecutor's +# config.toml, which still names the two # tasks until you edit it. This script is the recipe's counterpart to # install-tasks.ps1; GameModeExecutor itself does not know which recipe you # followed and never removes a task it did not register. diff --git a/docs/reference.md b/docs/reference.md index 27705f2..3707f62 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -8,7 +8,7 @@ for the reasons, the [design record](design/). | Executable | For | | --- | --- | | `gamemode-executor.exe` | Every command you type. A console program: a shell waits for it and gets its exit code. | -| `gamemode-executorw.exe` | The same commands, no console, prints nothing. Run by the logon task (`run`) and the installer (`stop`, `init`, `install-task`, `uninstall-task`). | +| `gamemode-executorw.exe` | The same commands, no console, prints nothing. Run by Windows at logon (`run`) and the installer (`stop`, `init`, `add-to-startup`, `remove-from-startup`). | | `presence-probe.exe` | Diagnostics, not shipped. See [Detection](design/00-detection.md#the-instrument). | ## Commands @@ -21,19 +21,21 @@ 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`. | -| `install-task [--delay 15s] [--force]` | Register the per-user logon task running `gamemode-executorw.exe`, and start it. An existing task is kept unless `--force`. | -| `uninstall-task` | Remove that task. | +| `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`. | +| `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. | -| `purge [--yes]` | Remove every trace: task, configuration, logs, session marker, updates folder, executables. Asks first; refuses during a game. | +| `purge [--yes]` | Remove every trace: startup entry, configuration, logs, session marker, updates folder, executables. Asks first; refuses during a game. | | `open ` | Hidden: the menu's helper, which opens a file or page the way Explorer would and exits. | Global options: `--config `, `--log-level `, `--version`. Without `--config`, `config.toml` next to the executable is used if present, else `%APPDATA%\GameModeExecutor\config.toml`. -The setup commands (`init`, `install-task`, `uninstall-task`, `stop`) log what -they did under `setup`, `update` under `update`. +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. ## Configuration @@ -167,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 | -| Logon task | `\GameModeExecutor\Watcher` | holds the executable's absolute path; removed on uninstall, kept on upgrade | +| 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. | | 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/scripts/build.ps1 b/scripts/build.ps1 index 40bf035..0bd6a14 100644 --- a/scripts/build.ps1 +++ b/scripts/build.ps1 @@ -349,16 +349,16 @@ by the time you follow it. Start there. INSTALLED FROM THE .MSI Nothing to do. The installer wrote a starter configuration if you had - none, registered the logon task and started the watcher: the icon beside + none, added the watcher to Startup and started it: the icon beside the clock is the confirmation. Right-click it, Edit configuration. GameModeExecutor in the Start menu starts the watcher again after Quit. UNPACKED FROM THE .ZIP - Keep this folder where you put it -- the logon task remembers the path. + Keep this folder where you put it -- the startup entry remembers the path. Then, from a terminal in this folder: gamemode-executor init writes a starter configuration - gamemode-executor install-task starts the watcher now and at every logon + gamemode-executor add-to-startup starts the watcher now and at every logon WHAT TO RUN The starter configuration runs nothing; the icon that appears shows the @@ -369,8 +369,8 @@ WHAT TO RUN THE TWO EXECUTABLES gamemode-executor.exe the one you talk to. Every command. It answers, then it is done. - gamemode-executorw.exe the one that works. No window, ever. It starts - itself at logon. You never launch it yourself. + gamemode-executorw.exe the one that works. No window, ever. Windows + starts it at logon. You never launch it yourself. UPDATING Right-click the icon, Check for updates. Nothing is checked unless you diff --git a/scripts/msi.ps1 b/scripts/msi.ps1 index 25465e1..accf904 100644 --- a/scripts/msi.ps1 +++ b/scripts/msi.ps1 @@ -4,18 +4,18 @@ # readme -- the same four files the zip carries -- go to # %LOCALAPPDATA%\Programs\GameModeExecutor, and an entry in the user's Start # menu starts the watcher. The user's configuration, log, -# marker and scheduled tasks are not components, so no repair, upgrade or +# marker and startup entry are not components, so no repair, upgrade or # uninstall reaches them. Five custom actions, all the program's own # commands and all idempotent, run through the windowless executable: # `stop --handover` before an upgrade touches the files and plain `stop` # before an uninstall does, so the Restart Manager never has to ask and a # game session in progress is resumed by the new watcher rather than # closed and reopened; `init`, which writes a starter configuration only -# where there is none, and `install-task`, which registers the logon task -# only where there is none and then starts the watcher -- the icon -# appearing is the confirmation -- to finish an install or upgrade; and -# `uninstall-task` on an uninstall, since the task is the package's to take -# down. +# where there is none, and `add-to-startup`, which adds the startup entry +# only where there is none and then has Explorer start the watcher -- the +# icon appearing is the confirmation -- to finish an install or upgrade; +# and `remove-from-startup` on an uninstall, since the entry is the +# package's to take down. # # Written with nothing but Windows Installer's own COM automation and # makecab, so a stock runner can build it -- docs/design/08-distribution.md @@ -278,7 +278,7 @@ try { } # The Start menu entry: the windowless executable, which starts the # watcher, or says in the log that one is already running and stops -- - # Quit's undo, for someone who does not know the logon task is there + # Quit's undo, for someone who does not know the startup entry is there # (the second machine, 2026-09-18). ProgramMenuFolder is the user's own # Start menu in a per-user install, so its component takes an HKCU value # as key path, as ICE38 and ICE43 require of anything in the profile. @@ -310,21 +310,24 @@ try { # because Windows Installer does not hide an action's console and the # console binary would flash one twice (seen 2026-09-18). Insert 'CustomAction' @('InitConfig', 1042, 'gamemode_executorw.exe', 'init', $null) - Insert 'CustomAction' @('RegisterTask', 1042, 'gamemode_executorw.exe', 'install-task', $null) - # The task is the package's infrastructure, not the user's data: left + # The startup entry, written by the program rather than a Registry row: + # the zip writes the same value through the same command, and one writer + # keeps a configuration path the user chose (Lot 19). The command also + # removes the logon task a 0.4 copy leaves, so nothing here is for 0.4. + Insert 'CustomAction' @('AddToStartup', 1042, 'gamemode_executorw.exe', 'add-to-startup', $null) + # The entry is the package's infrastructure, not the user's data: left # behind, it would start a missing executable at every logon and fail - # (the maintainer's remark on 2026-09-18). Removed on an uninstall, from - # the executable it runs before RemoveFiles takes it; kept through an - # upgrade, which re-registers nothing and so keeps a delay or a path the - # user chose. - Insert 'CustomAction' @('UnregisterTask', 1042, 'gamemode_executorw.exe', 'uninstall-task', $null) + # (the maintainer's remark on 2026-09-18, of the task then). Removed on + # an uninstall, by the executable it names, before RemoveFiles takes it; + # kept through an upgrade, which rewrites nothing. + Insert 'CustomAction' @('RemoveFromStartup', 1042, 'gamemode_executorw.exe', 'remove-from-startup', $null) # 98 = 34 (run a command line in a directory from the Directory table) # + 64 (carry on if it fails). Immediate, before InstallValidate, where # the Restart Manager would otherwise find the watcher holding the files # and put up its "close these applications" dialog (seen 2026-09-18 on # the first uninstall). Both run the *installed* executable, which an # upgrade has not replaced yet. An upgrade hands a game session over -- - # RegisterTask starts the new watcher seconds later and it resumes the + # AddToStartup starts the new watcher seconds later and it resumes the # session, nothing runs twice; a removal restores, since nobody follows. # An installed version too old to know the verb or the flag fails the # action, which continues, and the dialog comes back for that one @@ -341,8 +344,8 @@ try { @('RemoveExistingProducts', 1510), @('ProcessComponents', 1600), @('UnpublishFeatures', 1800), @('RemoveRegistryValues', 2600), @('RemoveShortcuts', 3200), - @('UnregisterTask', 3400), @('RemoveFiles', 3500), @('InstallFiles', 4000), - @('InitConfig', 4100), @('RegisterTask', 4200), + @('RemoveFromStartup', 3400), @('RemoveFiles', 3500), @('InstallFiles', 4000), + @('InitConfig', 4100), @('AddToStartup', 4200), @('CreateShortcuts', 4500), @('WriteRegistryValues', 5000), @('RegisterUser', 6000), @('RegisterProduct', 6100), @('PublishFeatures', 6300), @('PublishProduct', 6400), @@ -374,11 +377,11 @@ try { # stopped the watcher before it got here, and the first upgrade # (2026-09-18) logged a second, empty stop for nothing. $conditions = @{ - InitConfig = 'NOT Installed' - RegisterTask = 'NOT Installed' - StopForUpgrade = 'PREVIOUSVERSIONS' - StopForRemoval = 'REMOVE="ALL" AND NOT UPGRADINGPRODUCTCODE' - UnregisterTask = 'REMOVE="ALL" AND NOT UPGRADINGPRODUCTCODE' + InitConfig = 'NOT Installed' + AddToStartup = 'NOT Installed' + StopForUpgrade = 'PREVIOUSVERSIONS' + StopForRemoval = 'REMOVE="ALL" AND NOT UPGRADINGPRODUCTCODE' + RemoveFromStartup = 'REMOVE="ALL" AND NOT UPGRADINGPRODUCTCODE' } foreach ($t in $sequences.Keys) { foreach ($row in $sequences[$t]) { diff --git a/scripts/release-notes.ps1 b/scripts/release-notes.ps1 index 23d8380..3470f83 100644 --- a/scripts/release-notes.ps1 +++ b/scripts/release-notes.ps1 @@ -63,8 +63,8 @@ $lines = @( '', '## Install', '', - "- **GameModeExecutor-$version.msi** -- the installer. Per user, no administrator prompt, into ``%LOCALAPPDATA%\Programs\GameModeExecutor``. It writes a starter configuration if you have none, registers the logon task and starts the watcher: the icon beside the clock is the confirmation. Then right-click it, *Edit configuration*.", - "- **GameModeExecutor-$version.zip** -- the same executables, to unpack wherever you like. Then ``gamemode-executor init``, edit the file it wrote, ``gamemode-executor install-task``.", + "- **GameModeExecutor-$version.msi** -- the installer. Per user, no administrator prompt, into ``%LOCALAPPDATA%\Programs\GameModeExecutor``. It writes a starter configuration if you have none, adds the watcher to the programs Windows starts at logon and starts it: the icon beside the clock is the confirmation. Then right-click it, *Edit configuration*.", + "- **GameModeExecutor-$version.zip** -- the same executables, to unpack wherever you like. Then ``gamemode-executor init``, edit the file it wrote, ``gamemode-executor add-to-startup``.", "- **GameModeExecutor-recipes-$version.zip** -- the worked examples, one folder each, for this build.", '', "[Documentation for this exact build]($docs).", diff --git a/src/bin/gamemode-executorw.rs b/src/bin/gamemode-executorw.rs index 646b386..422cafb 100644 --- a/src/bin/gamemode-executorw.rs +++ b/src/bin/gamemode-executorw.rs @@ -1,5 +1,5 @@ #![windows_subsystem = "windows"] -//! The same program with no console, for the logon task and the installer. +//! The same program with no console, for logon and the installer. //! //! The twin of `gamemode-executor.exe`: the same commands from the same //! library, differing only in subsystem. The two subsystems cannot live in one @@ -11,9 +11,10 @@ //! through this binary would get its exit code before the verdict, and //! nothing this binary prints goes anywhere. That is why people type the //! console one and why the documentation only ever names it. This one is for -//! the two callers that have no console to give: the logon task, which runs -//! the watcher, and the installer, which runs `stop`, `init`, `install-task` -//! and `uninstall-task` -- Windows Installer starts an executable action +//! the two callers that have no console to give: Windows at logon, which +//! starts the watcher from the startup entry, and the installer, which runs +//! `stop`, `init`, `add-to-startup` and `remove-from-startup` -- Windows +//! Installer starts an executable action //! without hiding its console, and the console binary flashed a window twice //! at the end of every install, seen on 2026-09-18. The commands log what //! they did, so nothing is lost by not printing it; the exit code is what the @@ -30,7 +31,7 @@ fn main() -> std::process::ExitCode { let code = exit::code_for(&error); // There is no console to print to. The log file has the detail // when the command got as far as opening one, and the exit code - // is what Task Scheduler and Windows Installer record. + // is what Windows Installer records. if code == exit::ALREADY_RUNNING { // The Start menu entry starts this binary whether or not a // watcher runs; finding one is the answer, not a fault. diff --git a/src/cli.rs b/src/cli.rs index 7987832..f7487e4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -4,27 +4,27 @@ //! arguments and run the same commands; they differ in subsystem alone. The //! console one is the one people type, because a shell waits for it and its //! output and exit code arrive where a person or a script can see them. The -//! windowless one is what the logon task and the installer run: it prints -//! nothing, there is nowhere to print, and its exit code is the verdict. -//! Windows Installer starts an executable action without hiding its +//! windowless one is what Windows starts at logon and the installer runs: it +//! prints nothing, there is nowhere to print, and its exit code is the +//! verdict. Windows Installer starts an executable action without hiding its //! console, so the console binary would flash a window twice at the end of //! every install -- seen on 2026-09-18 -- which is why the installer runs -//! `init` and `install-task` through the twin. +//! `init` and `add-to-startup` through the twin. //! -//! `init`, `install-task`, `uninstall-task` and `stop` write what they did to +//! `init`, `add-to-startup`, `remove-from-startup` and `stop` write what they did to //! the log, under `setup`, at `info`: the log then says who did what to this //! machine and when, whether a person typed it or the installer ran it. use std::path::{Path, PathBuf}; -use anyhow::{Context, Result}; +use anyhow::Result; use clap::{Parser, Subcommand, ValueEnum}; use crate::config::{self, Config}; use crate::detect::known_games::KnownGames; use crate::detect::presence_writer; use crate::detect::process::Snapshot; -use crate::{actions, build_info, detect, logging, marker, purge, service, task}; +use crate::{actions, build_info, detect, logging, marker, purge, service, startup, task}; #[derive(Parser, Debug)] #[command( @@ -53,7 +53,7 @@ pub enum Command { /// Watch for games and run the configured actions (default). /// /// For an unattended instance use `gamemode-executorw.exe`, which is the - /// same watcher with no console at all. `install-task` registers that one. + /// 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 @@ -86,21 +86,23 @@ pub enum Command { #[arg(long)] force: bool, }, - /// Register a per-user logon task that starts the watcher hidden, and - /// start it now. A task already registered is kept. - InstallTask { - /// Delay after logon, e.g. `15s` or `1m`. - #[arg(long, default_value = "15s")] - delay: String, - /// Replace a task that is already registered. + /// Add the watcher to the programs Windows starts at logon -- Settings + /// lists it under Startup, with a switch -- and start it now. An entry + /// already there is kept. + // `install-task` is its name up to 0.4, still called by a 0.4 zip copy's + // updater: accepted until 1.0.0, decided 2026-11-16. + #[command(alias = "install-task")] + AddToStartup { + /// Replace an entry that is already there. #[arg(long)] force: bool, }, - /// Remove the logon task. - UninstallTask, + /// Remove the watcher from the programs Windows starts at logon. + #[command(alias = "uninstall-task")] + RemoveFromStartup, /// Stop the running watcher, the way Quit in its menu does: mid-game, /// the stop commands run on the way out. None running is not an error. - /// The logon task is left as it is; `install-task` starts it again. + /// The startup entry is left as it is; `add-to-startup` starts it again. Stop { /// Leave an open game session to the next watcher instead of /// closing it: the stop commands do not run, and the watcher that @@ -118,7 +120,7 @@ pub enum Command { #[arg(long)] check: bool, }, - /// Remove every trace of the program: the logon task, the configuration, + /// Remove every trace of the program: the startup entry, the configuration, /// the log, the session marker, and the executables themselves. Refuses /// while a game is running. Shows what it will remove and asks first. Purge { @@ -155,17 +157,16 @@ pub fn run(cli: Cli, console: bool) -> Result<()> { config::write_starter(&path, force)?; return Ok(()); } - Some(Command::InstallTask { delay, force }) => { + Some(Command::AddToStartup { force }) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; - let delay = humantime::parse_duration(&delay) - .with_context(|| format!("cannot read `{delay}` as a delay"))?; let path = resolve_config_path(cli.config)?; - task::install(&path, delay, force)?; + startup::add(&path, force)?; return Ok(()); } - Some(Command::UninstallTask) => { + Some(Command::RemoveFromStartup) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; - return task::uninstall(); + startup::remove()?; + return task::remove_leftover(); } Some(Command::Stop { handover }) => { setup_logging(cli.config.as_deref(), cli.log_level.as_deref(), console)?; @@ -634,16 +635,13 @@ mod tests { parse(&["init", "--force"]).command, Some(Command::Init { force: true }) )); - match parse(&["install-task", "--delay", "1m", "--force"]).command { - Some(Command::InstallTask { delay, force }) => { - assert_eq!(delay, "1m"); - assert!(force); - } - other => panic!("{other:?}"), - } assert!(matches!( - parse(&["uninstall-task"]).command, - Some(Command::UninstallTask) + parse(&["add-to-startup", "--force"]).command, + Some(Command::AddToStartup { force: true }) + )); + assert!(matches!( + parse(&["remove-from-startup"]).command, + Some(Command::RemoveFromStartup) )); assert!(matches!( parse(&["update", "--check"]).command, @@ -655,6 +653,25 @@ mod tests { )); } + /// A 0.4 zip copy's updater runs the new binary's `install-task`, so the + /// old names work until 1.0.0, without being offered. Remove this test + /// with them. + #[test] + fn the_old_names_of_the_startup_commands_still_work_unoffered() { + assert!(matches!( + parse(&["install-task"]).command, + Some(Command::AddToStartup { force: false }) + )); + assert!(matches!( + parse(&["uninstall-task"]).command, + Some(Command::RemoveFromStartup) + )); + use clap::CommandFactory; + let help = Cli::command().render_help().to_string(); + assert!(!help.contains("install-task"), "{help}"); + assert!(help.contains("add-to-startup"), "{help}"); + } + #[test] fn the_menus_helper_takes_what_to_open_and_is_not_offered() { // A path with spaces arrives whole: the watcher passes it as one diff --git a/src/lib.rs b/src/lib.rs index c490cca..e5daffc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod registry; pub mod sensor; pub mod service; pub mod shell; +pub mod startup; pub mod task; #[cfg(test)] mod testing; diff --git a/src/logging.rs b/src/logging.rs index d31ca5d..5f7a485 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -59,7 +59,7 @@ pub mod target { /// Running the executables from the configuration. pub const COMMANDS: &str = "commands"; /// Setting the program up and taking it down: the starter configuration, - /// the logon task. Written by the commands and by the installer alike, + /// the startup entry. Written by the commands and by the installer alike, /// so the log says who did what to this machine and when. pub const SETUP: &str = "setup"; /// Looking for, fetching and installing a newer release: the one thing diff --git a/src/purge.rs b/src/purge.rs index 9f30e30..35a7a7f 100644 --- a/src/purge.rs +++ b/src/purge.rs @@ -3,7 +3,8 @@ //! //! The rule, from `docs/design/08-distribution.md`: it removes what it //! recognises as its own and leaves the rest, saying what it left. Its own -//! is the logon task, the configuration wherever it was found, the log +//! is the startup entry with its switch, the logon task an earlier version +//! registered, the configuration wherever it was found, the log //! wherever it was written, the session marker, the updater's folder and //! what it holds, the two profile folders once they are empty, and last //! the executables -- through Windows @@ -13,7 +14,7 @@ //! know: left alone. //! //! The uninstall writes to the log once more: Windows Installer runs `stop` -//! and `uninstall-task`, and each says what it did, in the default log +//! and `remove-from-startup`, and each says what it did, in the default log //! folder since the configuration is gone by then. So the shell that runs //! the uninstall waits for it and sweeps that folder afterwards -- decided //! 2026-09-25 over a flag telling those commands not to log, which would @@ -38,6 +39,7 @@ use crate::marker; use crate::package; use crate::service; use crate::shell::{after_exit, quoted}; +use crate::startup; use crate::task; use crate::win; @@ -64,6 +66,8 @@ pub enum Program { #[derive(Debug, Clone, Default)] pub struct Layout { pub watcher_running: bool, + pub startup_entry: bool, + /// The logon task of a version up to 0.4, left by an upgrade. pub task_registered: bool, pub config_candidates: Vec, /// The log's folder: every log file in it goes, today's and the days @@ -87,6 +91,7 @@ pub struct Layout { #[derive(Debug, Clone, PartialEq, Eq)] pub struct Plan { pub stop_watcher: bool, + pub remove_startup: bool, pub remove_task: bool, pub files: Vec, /// Folders that are the program's own through and through, removed @@ -185,6 +190,7 @@ impl Plan { Self { stop_watcher: layout.watcher_running, + remove_startup: layout.startup_entry, remove_task: layout.task_registered, files, trees, @@ -195,6 +201,7 @@ impl Plan { pub fn is_empty(&self) -> bool { !self.stop_watcher + && !self.remove_startup && !self.remove_task && self.files.is_empty() && self.trees.is_empty() @@ -208,8 +215,17 @@ impl Plan { if self.stop_watcher { lines.push("stop the running watcher".to_owned()); } + if self.remove_startup { + lines.push(format!( + "remove the startup entry `{}` and its switch", + startup::VALUE_NAME + )); + } if self.remove_task { - lines.push(format!("remove the logon task `{}`", task::TASK_NAME)); + lines.push(format!( + "remove the logon task `{}` an earlier version registered", + task::TASK_NAME + )); } for file in &self.files { lines.push(format!("delete {}", file.display())); @@ -254,6 +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(), task_registered: task::exists(), config_candidates: candidates, log_dir, @@ -318,7 +335,7 @@ fn remove_empty_dir(dir: &Path) -> std::io::Result<()> { } /// The shell's steps for an installed copy: the uninstall, waited for, then -/// the log its `stop` and `uninstall-task` wrote and the folders that leaves +/// the log its `stop` and `remove-from-startup` wrote and the folders that leaves /// empty. fn uninstall_steps(product_code: &str, default_log_dir: Option<&Path>) -> Vec { let mut steps = vec![format!( @@ -345,8 +362,11 @@ pub fn execute(plan: &Plan) -> Result<()> { service::stop(win::StopReason::Restore)?; println!("Watcher stopped."); } + if plan.remove_startup { + startup::remove()?; + } if plan.remove_task { - task::uninstall()?; + task::remove_leftover()?; } for file in &plan.files { std::fs::remove_file(file).with_context(|| format!("cannot delete {}", file.display()))?; @@ -444,6 +464,7 @@ mod tests { touch(&exe_dir.join("LICENSE")); let layout = Layout { watcher_running: false, + startup_entry: true, task_registered: true, config_candidates: vec![exe_dir.join("config.toml"), roaming.join("config.toml")], log_dir: Some(local.join("logs")), @@ -460,6 +481,7 @@ mod tests { let plan = Plan::compute(&layout); assert!(!plan.stop_watcher); + assert!(plan.remove_startup); assert!(plan.remove_task); // The config next to the executable and the marker do not exist; // every log file goes, dated or from before the rotation, and a @@ -513,7 +535,7 @@ mod tests { assert!(plan.files.is_empty() && plan.dirs.is_empty()); } - /// The uninstall's `stop` and `uninstall-task` log what they did, after + /// The uninstall's `stop` and `remove-from-startup` log what they did, after /// the purge has deleted the log: the shell waits for the installer, /// then deletes the log files alone, then the two folders only if that /// left them empty. @@ -579,6 +601,7 @@ mod tests { touch(&kept.join("something-else.txt")); let plan = Plan { stop_watcher: false, + remove_startup: false, remove_task: false, files: vec![ local.join("logs").join("gamemode-executor.log"), diff --git a/src/startup.rs b/src/startup.rs new file mode 100644 index 0000000..9bdb07f --- /dev/null +++ b/src/startup.rs @@ -0,0 +1,403 @@ +//! Starting the watcher at logon from the user's `Run` key. +//! +//! Windows starts every program named under +//! `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` when the user logs +//! on, and the Startup page of Settings, like Task Manager's, lists each one +//! with a switch. Up to 0.4 a logon task started the watcher instead; Office's +//! updates end what a logon task started and spare what the `Run` key started, +//! measured from 2026-10-17 to 2026-11-16 (`docs/design/19-startup-list.md`). +//! +//! The rules this module keeps: +//! +//! - 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. +//! - 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. +//! - 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 +//! this command started itself would be the installer's child, which +//! nothing measured. If Explorer cannot be asked, the watcher waits for the +//! next logon, said at `warn`: an install must not fail for it. +//! +//! - The value is a command line of at most 260 characters, Microsoft's +//! limit; a longer one is refused rather than written cut. +//! + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use windows::Win32::System::Com::{ + CLSCTX_LOCAL_SERVER, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE, CoCreateInstance, + CoInitializeEx, CoUninitialize, IDispatch, IServiceProvider, +}; +use windows::Win32::System::Variant::VARIANT; +use windows::Win32::UI::Shell::{ + CSIDL_DESKTOP, IShellBrowser, IShellDispatch2, IShellFolderViewDual, IShellWindows, + SID_STopLevelBrowser, SVGIO_BACKGROUND, SWC_DESKTOP, SWFO_NEEDDISPATCH, ShellWindows, +}; +use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; +use windows::core::{BSTR, Interface}; +use windows_registry::CURRENT_USER; + +use crate::logging::target; + +/// The value's name under the `Run` key. The Startup page shows the +/// executable's description instead, *GameModeExecutor watcher*. +pub const VALUE_NAME: &str = "GameModeExecutor"; + +const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run"; + +/// Where Explorer keeps the Startup page's switches for the `Run` key. +const APPROVED_KEY: &str = + r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; + +/// The windowless twin the entry starts. Sits beside whichever binary runs +/// this command: the console one a person typed, or the twin itself when +/// the installer runs it. +const WATCHER_EXE: &str = "gamemode-executorw.exe"; + +/// Microsoft's limit on the value's command line. +const MAX_COMMAND_LINE: usize = 260; + +/// What `add` did about the entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Registration { + /// There was no entry; there is one now. + Added, + /// An entry was there and was left alone. + Kept, + /// An entry was there and `force` replaced it. + Replaced, +} + +/// The decision alone, so it can be tested without the registry. +pub fn registration(exists: bool, force: bool) -> Registration { + match (exists, force) { + (false, _) => Registration::Added, + (true, false) => Registration::Kept, + (true, true) => Registration::Replaced, + } +} + +/// The entry as it stands, if there is one. +pub fn entry() -> Option { + CURRENT_USER + .open(RUN_KEY) + .ok()? + .get_string(VALUE_NAME) + .ok() + .filter(|line| !line.is_empty()) +} + +/// 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 +/// single-instance mutex, so the second start exits at once. +/// +/// The installer calls this on every install and upgrade, and the zip's +/// updater after every update. Every outcome is logged at `info`, under +/// `setup`. +pub fn add(config_path: &Path, force: bool) -> Result { + let existing = entry(); + let outcome = registration(existing.is_some(), force); + let line = match (existing, outcome) { + (Some(line), Registration::Kept) => { + tracing::info!( + target: target::SETUP, + value = VALUE_NAME, + command = %line, + "Startup entry kept: one is already there (--force replaces it)" + ); + line + } + _ => { + let here = std::env::current_exe().context("cannot locate the running executable")?; + let exe = here.with_file_name(WATCHER_EXE); + if !exe.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() + ); + } + let line = command_line(&exe, &absolute(config_path)?)?; + CURRENT_USER + .create(RUN_KEY) + .and_then(|key| key.set_string(VALUE_NAME, &line)) + .with_context(|| format!("cannot write `{VALUE_NAME}` under HKCU\\{RUN_KEY}"))?; + if outcome == Registration::Added { + tracing::info!( + target: target::SETUP, + value = VALUE_NAME, + command = %line, + "Added to the programs Windows starts at logon; Settings lists it under Startup, with a switch" + ); + } else { + tracing::info!( + target: target::SETUP, + value = VALUE_NAME, + command = %line, + "Startup entry replaced, as asked" + ); + } + 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() { + 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" + ); + } + 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!( + target: target::SETUP, + value = VALUE_NAME, + "Removed from the programs Windows starts at logon" + ); + } else { + tracing::info!( + target: target::SETUP, + value = VALUE_NAME, + "No startup entry to remove" + ); + } + // 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!( + target: target::SETUP, + value = VALUE_NAME, + "The Startup page's switch for it removed" + ); + } + Ok(()) +} + +/// The value's data: the twin and the configuration it reads, both quoted. +fn command_line(exe: &Path, config: &Path) -> Result { + let line = format!("\"{}\" --config \"{}\"", exe.display(), config.display()); + let length = line.encode_utf16().count(); + if length > MAX_COMMAND_LINE { + bail!( + "the command line Windows would start at logon is {length} characters long, and \ + Windows reads at most {MAX_COMMAND_LINE}: `{line}`. A shorter path to the program \ + or to the configuration fits." + ); + } + Ok(line) +} + +/// A command line split into the program and what follows it, the way the +/// shell takes them. +fn split(line: &str) -> (&str, &str) { + let line = line.trim_start(); + if let Some(rest) = line.strip_prefix('"') { + match rest.find('"') { + Some(end) => (&rest[..end], rest[end + 1..].trim_start()), + None => (rest, ""), + } + } else { + match line.find(char::is_whitespace) { + Some(end) => (&line[..end], line[end..].trim_start()), + None => (line, ""), + } + } +} + +/// Have Explorer start what the entry names, and say how it went. +fn start(line: &str) { + let (program, parameters) = split(line); + match start_from_explorer(program, parameters) { + Ok(()) => tracing::info!( + target: target::SETUP, + program, + "Watcher started through Explorer; its icon appears in the notification area" + ), + Err(error) => tracing::warn!( + target: target::SETUP, + program, + error = %error, + "The watcher could not be started now, so it starts at the next logon" + ), + } +} + +/// `ShellExecute` run by Explorer rather than by this process: the desktop's +/// folder view, found through the shell's window list, hands out the shell +/// automation object of the Explorer that owns it, and what that object +/// 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<()> { + // 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) + .parent() + .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. + let started = unsafe { + (|| -> windows::core::Result<()> { + let windows: IShellWindows = + CoCreateInstance(&ShellWindows, None, CLSCTX_LOCAL_SERVER)?; + let location = VARIANT::from(CSIDL_DESKTOP as i32); + let root = VARIANT::default(); + let mut window = 0; + let desktop = windows.FindWindowSW( + &location, + &root, + SWC_DESKTOP, + &mut window, + SWFO_NEEDDISPATCH, + )?; + let browser: IShellBrowser = desktop + .cast::()? + .QueryService(&SID_STopLevelBrowser)?; + let view = browser.QueryActiveShellView()?; + let background: IDispatch = view.GetItemObject(SVGIO_BACKGROUND)?; + let shell: IShellDispatch2 = background + .cast::()? + .Application()? + .cast()?; + shell.ShellExecute( + &BSTR::from(program), + &VARIANT::from(parameters), + &VARIANT::from(directory.as_str()), + &VARIANT::from("open"), + &VARIANT::from(SW_SHOWNORMAL.0), + ) + })() + }; + if com.is_ok() { + // SAFETY: COM was initialised above on this thread, and every + // interface obtained under it has been released. + unsafe { CoUninitialize() }; + } + started +} + +/// Make a path absolute without requiring it to exist, and without the +/// `\\?\` prefix `canonicalize` adds -- the Startup page and the registry +/// show the command line to the user, and that prefix is noise in it. +fn absolute(path: &Path) -> Result { + let joined = if path.is_absolute() { + path.to_path_buf() + } else { + let here = std::env::current_dir().context("cannot read the current directory")?; + here.join(path) + }; + // `join` concatenates, it does not normalise: a path typed with forward + // slashes keeps them, and the value would read + // `C:\GameModeExecutor\.local/config.toml`. Windows accepts it, a person + // reading the entry should not have to. Re-collecting the components + // emits the platform separator throughout and drops any `.` on the way. + Ok(joined.components().collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_entry_is_added_once_and_replaced_only_on_request() { + assert_eq!(registration(false, false), Registration::Added); + assert_eq!(registration(false, true), Registration::Added); + assert_eq!(registration(true, false), Registration::Kept); + assert_eq!(registration(true, true), Registration::Replaced); + } + + /// The entry runs the windowless binary with the configuration and + /// nothing else: `run` is the default command, and an entry that names + /// no flag keeps working whatever later versions do with them. + #[test] + fn the_entry_quotes_both_paths_and_passes_only_the_configuration() { + let line = command_line( + Path::new(r"C:\Users\A B\Programs\gamemode-executorw.exe"), + Path::new(r"C:\Users\A B\config.toml"), + ) + .unwrap(); + assert_eq!( + line, + r#""C:\Users\A B\Programs\gamemode-executorw.exe" --config "C:\Users\A B\config.toml""# + ); + } + + #[test] + fn a_command_line_past_microsofts_limit_is_refused() { + let deep = format!(r"C:\{}\config.toml", "d".repeat(240)); + let error = command_line(Path::new(r"C:\gamemode-executorw.exe"), Path::new(&deep)) + .unwrap_err() + .to_string(); + assert!(error.contains("at most 260"), "{error}"); + } + + #[test] + fn a_command_line_splits_into_the_program_and_the_rest() { + assert_eq!( + split(r#""C:\A B\w.exe" --config "C:\A B\c.toml""#), + (r"C:\A B\w.exe", r#"--config "C:\A B\c.toml""#) + ); + assert_eq!( + split(r"C:\w.exe --config C:\c.toml"), + (r"C:\w.exe", r"--config C:\c.toml") + ); + assert_eq!(split(r#""C:\A B\w.exe""#), (r"C:\A B\w.exe", "")); + assert_eq!(split(r"C:\w.exe"), (r"C:\w.exe", "")); + } + + /// A relative path would resolve at logon against Explorer's working + /// directory, and the watcher would exit 3 with nobody watching. + #[test] + fn a_relative_configuration_path_is_made_absolute() { + let here = std::env::current_dir().unwrap(); + let made = absolute(Path::new(".local/config.toml")).unwrap(); + assert!(made.is_absolute(), "{}", made.display()); + assert!(made.starts_with(&here), "{}", made.display()); + + let already = Path::new(r"C:\elsewhere\config.toml"); + assert_eq!(absolute(already).unwrap(), already); + } + + /// The command line is shown to the user, so it should not carry the + /// separators of whatever shell added it. + #[test] + fn separators_are_normalised() { + let mixed = absolute(Path::new("./.local/config.toml")).unwrap(); + let shown = mixed.to_string_lossy(); + assert!(!shown.contains('/'), "{shown}"); + assert!(shown.ends_with(r"\.local\config.toml"), "{shown}"); + + let absolute_but_mixed = absolute(Path::new("C:/elsewhere/config.toml")).unwrap(); + assert_eq!( + absolute_but_mixed, + Path::new(r"C:\elsewhere\config.toml"), + "{}", + absolute_but_mixed.display() + ); + } +} diff --git a/src/task.rs b/src/task.rs index 88d403f..476bfc4 100644 --- a/src/task.rs +++ b/src/task.rs @@ -1,284 +1,52 @@ -//! Registration as a per-user logon task. +//! The logon task that started the watcher up to 0.4, now only removed. //! -//! Registered from an XML definition rather than `schtasks` command-line flags, -//! because the defaults those flags leave behind are wrong for a watcher meant -//! to run forever: a 72 hour execution limit that kills it after three days, -//! and battery settings that stop it on an unplugged laptop. +//! Since Lot 19 the watcher starts from the user's `Run` key (`startup`). A +//! copy upgraded from 0.4 still has its task, which would start a second +//! watcher at logon -- usually the first one, and the one Office's updates +//! 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. -use std::path::Path; use std::process::Command; -use std::time::Duration; use anyhow::{Context, Result, bail}; -/// Task Scheduler folder everything this program installs lives in, rather than -/// scattered across the root alongside Windows' own tasks. `schtasks` creates -/// it on demand, so nothing has to make it first. -pub const TASK_FOLDER: &str = "GameModeExecutor"; - -/// The watcher's task, folder included. Named `Watcher` rather than repeating -/// the folder's name, so it reads as `GameModeExecutor \ Watcher` in the tree. +/// 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 +/// may live in it, and they are the user's. pub const TASK_NAME: &str = "GameModeExecutor\\Watcher"; -/// The windowless twin this task is meant to run. Sits beside whichever -/// binary is running this command: the console one a person typed, or the -/// twin itself when the installer runs it. -const WATCHER_EXE: &str = "gamemode-executorw.exe"; - -/// What `install` did about the task. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Registration { - /// There was no task; there is one now. - Registered, - /// A task was there and was left alone. - Kept, - /// A task was there and `force` replaced it. - Replaced, -} - -/// The decision alone, so it can be tested without Task Scheduler. -pub fn registration(exists: bool, force: bool) -> Registration { - match (exists, force) { - (false, _) => Registration::Registered, - (true, false) => Registration::Kept, - (true, true) => Registration::Replaced, - } -} - -/// Register the logon task that starts the watcher with no console, then -/// start it, so the icon appears now rather than at the next logon. Runs -/// only while the user is logged on, so no password and no elevation. -/// -/// A task that is already there is kept unless `force`: the installer calls -/// this on every install and upgrade, and must not undo a delay or a path -/// the user chose. Decided 2026-09-17, on the first install from the package. -/// Every outcome is logged at `info`, under `setup`. -pub fn install(config_path: &Path, delay: Duration, force: bool) -> Result { - let outcome = registration(exists(), force); - if outcome == Registration::Kept { - tracing::info!( - target: crate::logging::target::SETUP, - task = TASK_NAME, - "Logon task kept: one is already registered (--force replaces it)" - ); - start()?; - return Ok(outcome); - } - let here = std::env::current_exe().context("cannot locate the running executable")?; - let exe = here.with_file_name(WATCHER_EXE); - if !exe.exists() { - bail!( - "`{}` is missing. It is built alongside this program and is the one the task \ - runs, because it has no console to leave on screen.", - exe.display() - ); - } - // The task runs from whatever working directory Task Scheduler feels like, - // so a relative path here would resolve at logon against somewhere else and - // the watcher would exit 3 before anyone noticed. Absolute, always. - let config_path = absolute(config_path)?; - - let user = current_user().context("cannot determine the current user")?; - let xml = definition( - &exe.to_string_lossy(), - &config_path.to_string_lossy(), - &user, - delay, - ); - - let temp = std::env::temp_dir().join("GameModeExecutor-task.xml"); - write_utf16(&temp, &xml).with_context(|| format!("cannot write `{}`", temp.display()))?; - let result = run_schtasks(&[ - "/Create", - "/TN", - TASK_NAME, - "/XML", - &temp.to_string_lossy(), - "/F", - ]); - let _ = std::fs::remove_file(&temp); - result?; - - match outcome { - Registration::Registered => tracing::info!( - target: crate::logging::target::SETUP, - task = TASK_NAME, - user = %user, - program = %exe.display(), - config = %config_path.display(), - delay = ?delay, - "Logon task registered: it starts the watcher at every logon, with no execution time limit" - ), - _ => tracing::info!( - target: crate::logging::target::SETUP, - task = TASK_NAME, - user = %user, - program = %exe.display(), - config = %config_path.display(), - delay = ?delay, - "Logon task replaced, as asked" - ), - } - start()?; - Ok(outcome) -} - -/// Run the task now. A watcher already running keeps the single-instance -/// mutex, so a second start exits at once and nothing doubles. -fn start() -> Result<()> { - run_schtasks(&["/Run", "/TN", TASK_NAME])?; - tracing::info!( - target: crate::logging::target::SETUP, - task = TASK_NAME, - "Watcher started through its task; its icon appears in the notification area" - ); - Ok(()) +/// Whether that task is registered. `schtasks /Query` exits non-zero for a +/// task that does not exist, which is the whole answer. +pub fn exists() -> bool { + schtasks(&["/Query", "/TN", TASK_NAME]) + .output() + .map(|output| output.status.success()) + .unwrap_or(false) } -/// Remove the logon task. A task that is not there is not an error: the -/// outcome is logged either way. -pub fn uninstall() -> Result<()> { +/// Remove that task if it is there, saying so at `info`; nothing to say +/// when it is not. +pub fn remove_leftover() -> Result<()> { if !exists() { - tracing::info!( - target: crate::logging::target::SETUP, - task = TASK_NAME, - "No logon task to remove" - ); return Ok(()); } - run_schtasks(&["/Delete", "/TN", TASK_NAME, "/F"])?; - // The folder is left behind on purpose: anything else the user put in it -- - // the elevated tasks a recipe asks for, for instance -- is theirs, and - // removing a folder that still holds their work would be worse than - // leaving an empty one they can delete in a click. + let output = schtasks(&["/Delete", "/TN", TASK_NAME, "/F"]) + .output() + .context("cannot run schtasks.exe")?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + bail!("schtasks failed: {}", format!("{stdout}{stderr}").trim()); + } tracing::info!( target: crate::logging::target::SETUP, task = TASK_NAME, - folder = TASK_FOLDER, - "Logon task removed; the folder in Task Scheduler is left in place, empty or not" + "Logon task of an earlier version removed; the startup entry starts the watcher now" ); Ok(()) } -fn definition(exe: &str, config: &str, user: &str, delay: Duration) -> String { - format!( - r#" - - - Watches for a running game and runs the configured commands. Started at logon, unelevated. - \{name} - - - - true - {user} - {delay} - - - - - {user} - InteractiveToken - LeastPrivilege - - - - IgnoreNew - false - false - true - true - false - - false - false - - true - true - false - false - false - PT0S - 7 - - PT1M - 3 - - - - - {exe} - --config "{config}" - - - -"#, - name = escape(TASK_NAME), - user = escape(user), - delay = iso8601(delay), - exe = escape(exe), - config = escape(config), - ) -} - -/// Make a path absolute without requiring it to exist, and without the `\\?\` -/// prefix `canonicalize` adds -- Task Scheduler shows the command line to the -/// user, and that prefix is noise in it. -fn absolute(path: &Path) -> Result { - let joined = if path.is_absolute() { - path.to_path_buf() - } else { - let here = std::env::current_dir().context("cannot read the current directory")?; - here.join(path) - }; - // `join` concatenates, it does not normalise: a path typed with forward - // slashes keeps them, and the result is a command line reading - // `C:\GameModeExecutor\.local/config.toml`. Windows accepts - // it, a person reading the task's properties should not have to. - // Re-collecting the components emits the platform separator throughout and - // drops any `.` along the way. - Ok(joined.components().collect()) -} - -/// Task Scheduler durations are ISO 8601. Seconds are enough here. -fn iso8601(delay: Duration) -> String { - format!("PT{}S", delay.as_secs()) -} - -fn escape(value: &str) -> String { - value - .replace('&', "&") - .replace('<', "<") - .replace('>', ">") - .replace('"', """) -} - -/// Task Scheduler expects UTF-16 with a BOM, as it exports itself. -fn write_utf16(path: &Path, text: &str) -> std::io::Result<()> { - let mut bytes = vec![0xFF, 0xFE]; - for unit in text.replace('\n', "\r\n").encode_utf16() { - bytes.extend_from_slice(&unit.to_le_bytes()); - } - std::fs::write(path, bytes) -} - -fn current_user() -> Option { - let name = std::env::var("USERNAME").ok()?; - match std::env::var("USERDOMAIN") { - Ok(domain) if !domain.is_empty() => Some(format!("{domain}\\{name}")), - _ => Some(name), - } -} - -/// Whether the logon task is registered. `schtasks /Query` exits non-zero -/// for a task that does not exist, which is the whole answer. -pub fn exists() -> bool { - schtasks(&["/Query", "/TN", TASK_NAME]) - .output() - .map(|output| output.status.success()) - .unwrap_or(false) -} - /// `schtasks.exe` with its output captured and no console window of its /// own. A console program started from a parent that has no visible console /// -- the installer's custom action, the windowless watcher -- opens one for @@ -291,121 +59,3 @@ fn schtasks(args: &[&str]) -> Command { command.args(args).creation_flags(CREATE_NO_WINDOW); command } - -fn run_schtasks(args: &[&str]) -> Result<()> { - let output = schtasks(args).output().context("cannot run schtasks.exe")?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let stdout = String::from_utf8_lossy(&output.stdout); - bail!("schtasks failed: {}", format!("{stdout}{stderr}").trim()); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_task_is_registered_once_and_replaced_only_on_request() { - assert_eq!(registration(false, false), Registration::Registered); - assert_eq!(registration(false, true), Registration::Registered); - assert_eq!(registration(true, false), Registration::Kept); - assert_eq!(registration(true, true), Registration::Replaced); - } - - #[test] - fn the_definition_disables_the_traps() { - let xml = definition( - r"C:\tools\gamemode-executor.exe", - r"C:\config.toml", - r"PC\me", - Duration::from_secs(15), - ); - // The three settings whose schtasks defaults break a long-running watcher. - assert!(xml.contains("PT0S")); - assert!(xml.contains("false")); - assert!(xml.contains("false")); - // And it must stay unelevated. - assert!(xml.contains("LeastPrivilege")); - assert!(xml.contains("PT15S")); - } - - /// The URI has to carry the folder too, or the task registers at the path - /// `/TN` asks for while describing itself as living somewhere else. - #[test] - fn the_task_lives_in_its_own_folder() { - let xml = definition( - r"C:\tools\gamemode-executorw.exe", - r"C:\config.toml", - r"PC\me", - Duration::ZERO, - ); - assert_eq!(TASK_NAME, format!(r"{TASK_FOLDER}\Watcher")); - assert!(xml.contains(&format!(r"\{TASK_NAME}")), "{xml}"); - } - - /// The task runs the windowless binary with the configuration and nothing - /// else. `run` is the default command and `--hidden` is a leftover kept - /// for tasks registered before the twin existed; a definition that - /// names neither keeps working whatever later versions do with them, - /// and a task that fails at logon fails where nobody sees it. - #[test] - fn the_task_passes_only_the_configuration() { - let xml = definition( - r"C:\tools\gamemode-executorw.exe", - r"C:\config.toml", - r"PC\me", - Duration::from_secs(15), - ); - assert!( - xml.contains(r#"--config "C:\config.toml""#), - "{xml}" - ); - assert!(!xml.contains("--hidden"), "{xml}"); - } - - #[test] - fn xml_special_characters_are_escaped() { - let xml = definition("C:\\a&b.exe", "C:\\.toml", "PC\\me", Duration::ZERO); - assert!(xml.contains("C:\\a&b.exe")); - assert!(xml.contains("<config>")); - } - - /// A relative path would resolve at logon against Task Scheduler's own - /// working directory, and the watcher would exit 3 with nobody watching. - #[test] - fn a_relative_configuration_path_is_made_absolute() { - let here = std::env::current_dir().unwrap(); - let made = absolute(Path::new(".local/config.toml")).unwrap(); - assert!(made.is_absolute(), "{}", made.display()); - assert!(made.starts_with(&here), "{}", made.display()); - - let already = Path::new(r"C:\elsewhere\config.toml"); - assert_eq!(absolute(already).unwrap(), already); - } - - /// The task's command line is shown to the user in Task Scheduler, so it - /// should not carry the separators of whatever shell registered it. - #[test] - fn separators_are_normalised() { - let mixed = absolute(Path::new("./.local/config.toml")).unwrap(); - let shown = mixed.to_string_lossy(); - assert!(!shown.contains('/'), "{shown}"); - assert!(shown.ends_with(r"\.local\config.toml"), "{shown}"); - - let absolute_but_mixed = absolute(Path::new("C:/elsewhere/config.toml")).unwrap(); - assert_eq!( - absolute_but_mixed, - Path::new(r"C:\elsewhere\config.toml"), - "{}", - absolute_but_mixed.display() - ); - } - - #[test] - fn durations_become_iso8601() { - assert_eq!(iso8601(Duration::from_secs(15)), "PT15S"); - assert_eq!(iso8601(Duration::ZERO), "PT0S"); - } -} diff --git a/src/update/install.rs b/src/update/install.rs index 4a3d76c..94c0394 100644 --- a/src/update/install.rs +++ b/src/update/install.rs @@ -4,10 +4,12 @@ //! An installed copy hands the package to `msiexec /qn` through a hidden //! shell that waits for it: the package itself stops this watcher with a //! handover and starts the new one, so on success nothing here is left to -//! do; on failure the shell writes why and runs the logon task, so the +//! do; on failure the shell writes why and runs `add-to-startup`, so the //! previous watcher comes back and reports it. An unpacked copy's shell //! waits for this process to exit, expands the archive over the folder -//! with the old executables kept as `.old`, and runs `install-task`. +//! with the old executables kept as `.old`, and runs `add-to-startup`. +//! A 0.4 copy's shell runs `install-task` instead, the same command's old +//! name, and on an installer's failure the task it still has. //! //! `pending.txt` is written before anything is launched and read by //! whichever watcher starts next: the same version, the update took; @@ -147,8 +149,10 @@ fn tidy(context: &Context, all: bool) { } /// The shell line for an installed copy: `msiexec /qn` waited for, and on -/// failure a note and the logon task, so the previous watcher comes back. -fn installer_script(file: &Path, log: &Path, result: &Path) -> String { +/// failure a note and `add-to-startup` from the installed folder, where +/// Windows Installer's rollback put the previous executables back, so the +/// previous watcher comes back. +fn installer_script(file: &Path, log: &Path, result: &Path, install_dir: &Path) -> String { [ format!( "$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', {}, '/qn', '/l*v', {}) -Wait -PassThru", @@ -156,9 +160,9 @@ fn installer_script(file: &Path, log: &Path, result: &Path) -> String { shell::quoted(log) ), format!( - "if ($p.ExitCode -ne 0) {{ Set-Content -LiteralPath {} -Value ('Windows Installer ' + $p.ExitCode); schtasks /Run /TN '{}' | Out-Null }}", + "if ($p.ExitCode -ne 0) {{ Set-Content -LiteralPath {} -Value ('Windows Installer ' + $p.ExitCode); & {} add-to-startup }}", shell::quoted(result), - crate::task::TASK_NAME + shell::quoted(&install_dir.join("gamemode-executorw.exe")) ), ] .join("; ") @@ -166,8 +170,8 @@ fn installer_script(file: &Path, log: &Path, result: &Path) -> String { /// The shell line for an unpacked copy: wait for the process `pid`, expand /// the archive, keep the old executables as `.old`, copy the new files -/// over, `install-task`. On any failure: a note, the old executables back, -/// `install-task` all the same, so a watcher runs either way. +/// over, `add-to-startup`. On any failure: a note, the old executables back, +/// `add-to-startup` all the same, so a watcher runs either way. fn zip_script( pid: u32, file: &Path, @@ -194,7 +198,7 @@ fn zip_script( "Copy-Item -Path (Join-Path {} '*') -Destination {dir} -Recurse -Force -ErrorAction Stop", shell::quoted(source) ), - format!("& {twin} install-task"), + format!("& {twin} add-to-startup"), "} catch {".to_owned(), format!( "Set-Content -LiteralPath {} -Value ('zip: ' + $_.Exception.Message)", @@ -203,7 +207,7 @@ fn zip_script( format!( "foreach ($n in {names}) {{ $old = Join-Path {dir} ($n + '.old'); if (Test-Path -LiteralPath $old) {{ Move-Item -LiteralPath $old -Destination (Join-Path {dir} $n) -Force }} }}" ), - format!("& {twin} install-task"), + format!("& {twin} add-to-startup"), "}".to_owned(), ] .join("; ") @@ -218,7 +222,8 @@ pub fn launch(context: &Context, release: &Release, file: &Path) -> Result { - let script = installer_script(file, &dir.join(INSTALL_LOG), &result); + let script = + installer_script(file, &dir.join(INSTALL_LOG), &result, &context.install_dir); tracing::info!( target: target::UPDATE, package = %file.display(), @@ -434,6 +439,7 @@ mod tests { Path::new(r"C:\u\it's\GameModeExecutor-0.2.0.msi"), Path::new(r"C:\u\install.log"), Path::new(r"C:\u\result.txt"), + Path::new(r"C:\Programs\GME"), ); assert!(script.contains("'msiexec.exe'")); assert!(script.contains("'/qn'"), "no window"); @@ -443,7 +449,11 @@ mod tests { ); assert!(script.contains("-Wait -PassThru")); assert!(script.contains("'Windows Installer ' + $p.ExitCode")); - assert!(script.contains(r"schtasks /Run /TN 'GameModeExecutor\Watcher'")); + assert!( + script.contains(r"& 'C:\Programs\GME\gamemode-executorw.exe' add-to-startup"), + "{script}" + ); + assert!(!script.contains("schtasks"), "{script}"); } #[test] @@ -468,9 +478,11 @@ mod tests { ) ); assert_eq!( - script.matches("install-task").count(), + script + .matches(r"& 'C:\Tools\GME\gamemode-executorw.exe' add-to-startup") + .count(), 2, - "restarted on success and on failure" + "restarted on success and on failure: {script}" ); assert!(script.contains("} catch {")); assert!(script.contains("'zip: ' + $_.Exception.Message")); diff --git a/src/update/mod.rs b/src/update/mod.rs index c27d318..a7f2f8b 100644 --- a/src/update/mod.rs +++ b/src/update/mod.rs @@ -448,14 +448,16 @@ pub struct Context { /// The kind of copy this is, when pinned -- the tests pin it. `None` /// means it is decided when asked, from what Windows Installer says at /// that moment, never at start: the package starts the watcher from - /// `RegisterTask`, which runs *before* `RegisterProduct`, so a watcher + /// `AddToStartup` (`RegisterTask` up to 0.4), which runs *before* + /// `RegisterProduct`, so a watcher /// that decided at start saw no product and took itself for an /// unpacked copy. Seen on 2026-09-18 17:44 -- it expanded the zip over /// the package's folder. pub kind: Option, /// Where downloads go: `%LOCALAPPDATA%\GameModeExecutor\updates`. pub updates_dir: PathBuf, - /// Where the executables live, for the zip path. + /// Where the executables live: the zip path updates them there, and both + /// paths start the watcher from there again after a failure. pub install_dir: PathBuf, /// The running watcher's stop, when there is one: the zip path stops /// this process itself, with a handover, once its shell is started.