Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,13 @@ This file says how to work here. The *why* is in
`GameModeExecutor\FanControl` became `GameModeExecutorFanControl`,
`target\release` a carriage return. Edit with a tool that takes literal
strings, and grep the result.
- **A Windows path is written with single backslashes** wherever nothing
reads `\` as an escape: Rust raw strings (`r"C:\…"`, `format!(r"HKCU\{key}")`),
PowerShell, Markdown, TOML single quotes, the log. Escape only where the
format demands it, through one function: rc.exe's scripts (`rc_string` in
`build.rs`), PowerShell's single quotes (`shell::quoted`), JSON. A log
field is never `Debug`-formatted text: the formatter quotes text as
written, and a path given to `%` prints as Windows writes it.
- A shell started by a packaged host — the Claude desktop app — may read
`%APPDATA%` through the package's private copy. What the watcher runs is
in its log; ask the maintainer for the real file.
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ a section is written.

## [Unreleased]

### Fixed

- The log writes Windows paths as Windows does, with single backslashes,
where its details doubled them; a command's arguments read as typed.

## [0.5.0] - 2026-11-16

Windows' Startup list starts the watcher now, with a switch in Settings,
Expand Down
99 changes: 56 additions & 43 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ fn embed_resources(commit_short: &str, dirty: bool) {
.unwrap_or_default();
let flags = if dirty { "0x8" } else { "0x0" }; // VS_FF_PRIVATEBUILD
let private = if dirty {
" VALUE \"PrivateBuild\", \"Built from a tree with uncommitted changes\\0\"\n"
concat!(
r#" VALUE "PrivateBuild", "Built from a tree with uncommitted changes\0""#,
"\n"
)
} else {
""
};
Expand All @@ -130,53 +133,54 @@ fn embed_resources(commit_short: &str, dirty: bool) {
// application icon, and 1 is the convention for it. The numeric
// constants are rc.exe's own, spelled out so no header is needed:
// FILEOS 0x40004 is VOS_NT_WINDOWS32, FILETYPE 1 is VFT_APP, and the
// string block is en-US in Unicode.
// string block is en-US in Unicode. The script is rc.exe's language,
// where `\` begins an escape inside a quoted string: every value put
// in one goes through `rc_string`, and each `\0` written here is the
// terminator rc.exe expects.
let contents = format!(
concat!(
"1 ICON \"{icon}\"\n",
"1 VERSIONINFO\n",
"FILEVERSION {major},{minor},{patch},0\n",
"PRODUCTVERSION {major},{minor},{patch},0\n",
"FILEFLAGSMASK 0x3f\n",
"FILEFLAGS {flags}\n",
"FILEOS 0x40004\n",
"FILETYPE 0x1\n",
"FILESUBTYPE 0x0\n",
"BEGIN\n",
" BLOCK \"StringFileInfo\"\n",
" BEGIN\n",
" BLOCK \"040904b0\"\n",
" BEGIN\n",
" VALUE \"CompanyName\", \"{author}\\0\"\n",
" VALUE \"FileDescription\", \"{description}\\0\"\n",
" VALUE \"FileVersion\", \"{version} ({commit})\\0\"\n",
" VALUE \"InternalName\", \"{name}\\0\"\n",
" VALUE \"LegalCopyright\", \"{copyright}. MIT License.\\0\"\n",
" VALUE \"OriginalFilename\", \"{name}.exe\\0\"\n",
" VALUE \"ProductName\", \"GameModeExecutor\\0\"\n",
" VALUE \"ProductVersion\", \"{version}\\0\"\n",
" VALUE \"Comments\", \"{repository}\\0\"\n",
"{private}",
" END\n",
" END\n",
" BLOCK \"VarFileInfo\"\n",
" BEGIN\n",
" VALUE \"Translation\", 0x409, 1200\n",
" END\n",
"END\n",
),
icon = icon.display().to_string().replace('\\', "\\\\"),
r#"1 ICON "{icon}"
1 VERSIONINFO
FILEVERSION {major},{minor},{patch},0
PRODUCTVERSION {major},{minor},{patch},0
FILEFLAGSMASK 0x3f
FILEFLAGS {flags}
FILEOS 0x40004
FILETYPE 0x1
FILESUBTYPE 0x0
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "CompanyName", "{author}\0"
VALUE "FileDescription", "{description}\0"
VALUE "FileVersion", "{version} ({commit})\0"
VALUE "InternalName", "{name}\0"
VALUE "LegalCopyright", "{copyright}. MIT License.\0"
VALUE "OriginalFilename", "{name}.exe\0"
VALUE "ProductName", "GameModeExecutor\0"
VALUE "ProductVersion", "{version}\0"
VALUE "Comments", "{repository}\0"
{private} END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
"#,
icon = rc_string(&icon.display().to_string()),
major = major,
minor = minor,
patch = patch,
flags = flags,
author = author,
description = description,
version = version,
commit = commit_short,
name = name,
copyright = copyright,
repository = repository,
author = rc_string(&author),
description = rc_string(description),
version = rc_string(&version),
commit = rc_string(commit_short),
name = rc_string(name),
copyright = rc_string(&copyright),
repository = rc_string(&repository),
private = private,
);
if std::fs::write(&script, contents).is_err() {
Expand All @@ -201,6 +205,15 @@ fn embed_resources(commit_short: &str, dirty: bool) {
}
}

/// A value for a quoted string in rc.exe's script, where `\` begins an
/// escape as in C and a quote is written twice. The icon's path is the one
/// value with backslashes today; the others go through it too, so a quote
/// in a description or a backslash in a copyright line cannot break the
/// script.
fn rc_string(value: &str) -> String {
value.replace('\\', r"\\").replace('"', r#""""#)
}

/// Finds the SDK's resource compiler: the developer prompt's own variable
/// first, then the newest version under the installed Windows Kit.
fn find_resource_compiler() -> Option<std::path::PathBuf> {
Expand Down
33 changes: 32 additions & 1 deletion src/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,33 @@ fn start(action: &Action, context: &ActionContext) -> Result<Child> {
command.env(key, context.render(value));
}

tracing::debug!(target: target::COMMANDS, program, args = ?args, "Starting a command");
tracing::debug!(
target: target::COMMANDS,
program,
args = %shown_arguments(&args),
"Starting a command"
);
command
.spawn()
.with_context(|| format!("cannot start `{program}`"))
}

/// The arguments as a person would type them after the program, for the
/// log: one holding a space between quotes, nothing escaped, so a path
/// reads as Windows writes it. Not the command line `Command` builds.
fn shown_arguments(args: &[String]) -> String {
args.iter()
.map(|arg| {
if arg.is_empty() || arg.contains(char::is_whitespace) {
format!("\"{arg}\"")
} else {
arg.clone()
}
})
.collect::<Vec<_>>()
.join(" ")
}

/// `None` when the command was not waited for; otherwise whether it succeeded.
fn join(action: &Action, mut child: Child) -> Option<bool> {
if !action.wait {
Expand Down Expand Up @@ -247,6 +268,16 @@ mod tests {
Event { mode, actions }
}

/// The recipe's own command, as the log shows it.
#[test]
fn the_arguments_read_in_the_log_as_typed() {
let args = [r"/Run", r"/TN", r"GameModeExecutor\FanControl Game", ""].map(str::to_owned);
assert_eq!(
shown_arguments(&args),
r#"/Run /TN "GameModeExecutor\FanControl Game" """#
);
}

#[test]
fn a_series_reports_each_waited_command_and_keeps_going_after_a_failure() {
let outcome = run_all(
Expand Down
2 changes: 1 addition & 1 deletion src/bin/presence-probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ fn cmd_watch_games(seconds: u64, key: &str) -> windows::core::Result<()> {
let root = match Key::open_current_user(key) {
Ok(root) => root,
Err(error) => {
log(&format!("watch-games: cannot open HKCU\\{key} ({error:#})"));
log(&format!(r"watch-games: cannot open HKCU\{key} ({error:#})"));
return Ok(());
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/detect/presence_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn registered_exe() -> Result<PathBuf> {
.context("the presence writer server is not registered on this machine")?;
let path = key
.string_value(EXE_PATH_VALUE)
.with_context(|| format!("{SERVER_KEY}\\{EXE_PATH_VALUE} is empty"))?;
.with_context(|| format!(r"{SERVER_KEY}\{EXE_PATH_VALUE} is empty"))?;
Ok(PathBuf::from(path))
}

Expand Down
18 changes: 17 additions & 1 deletion src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,14 @@ impl Collected {
}

impl Visit for Collected {
/// A text field between quotes, as written: `Debug` would escape every
/// backslash of a Windows path, and the log is read by people, not
/// parsed.
fn record_str(&mut self, field: &Field, value: &str) {
if field.name() == "message" {
self.message.push_str(value);
} else {
self.push_field(field.name(), format_args!("{value:?}"));
self.push_field(field.name(), format_args!("\"{value}\""));
}
}

Expand Down Expand Up @@ -525,6 +528,19 @@ mod tests {
assert!(line.contains(r#"matched_by="exe path""#), "{line}");
}

/// A Windows path reads as Windows writes it: `Debug` once doubled every
/// backslash of a text field (until 2026-11-16).
#[test]
fn a_text_field_is_quoted_and_not_escaped() {
let line = render(true, || {
tracing::info!(target: target::GAME, path = r"D:\Games\Euro Truck Simulator 2\eurotrucks2.exe", "Game detected: eurotrucks2.exe");
});
assert!(
line.contains(r#"path="D:\Games\Euro Truck Simulator 2\eurotrucks2.exe""#),
"{line}"
);
}

/// Optional data is the common case here -- a game Windows tracks but does
/// not describe has no pid and no path -- so pin down how it renders
/// rather than discovering `pid=Some(14552)` in a log someone is reading.
Expand Down
4 changes: 2 additions & 2 deletions src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ impl Key {
CURRENT_USER
.open(path)
.map(Self)
.with_context(|| format!("cannot open HKCU\\{path}"))
.with_context(|| format!(r"cannot open HKCU\{path}"))
}

/// Open a key under `HKEY_LOCAL_MACHINE` for reading.
pub fn open_local_machine(path: &str) -> Result<Self> {
LOCAL_MACHINE
.open(path)
.map(Self)
.with_context(|| format!("cannot open HKLM\\{path}"))
.with_context(|| format!(r"cannot open HKLM\{path}"))
}

pub fn open_subkey(&self, name: &str) -> Result<Self> {
Expand Down
6 changes: 3 additions & 3 deletions src/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ pub fn add(config_path: &Path, force: bool) -> Result<Registration> {
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}"))?;
.with_context(|| format!(r"cannot write `{VALUE_NAME}` under HKCU\{RUN_KEY}"))?;
if outcome == Registration::Added {
tracing::info!(
target: target::SETUP,
Expand Down Expand Up @@ -219,7 +219,7 @@ fn remove_from(path: &str) -> Result<bool> {
return Ok(false);
}
key.remove_value(VALUE_NAME)
.with_context(|| format!("cannot remove `{VALUE_NAME}` from HKCU\\{path}"))?;
.with_context(|| format!(r"cannot remove `{VALUE_NAME}` from HKCU\{path}"))?;
Ok(true)
}

Expand All @@ -244,7 +244,7 @@ fn same_file(a: &Path, b: &Path) -> bool {

/// The value's data: the twin and the configuration it reads, both quoted.
fn command_line(exe: &Path, config: &Path) -> Result<String> {
let line = format!("\"{}\" --config \"{}\"", exe.display(), config.display());
let line = format!(r#""{}" --config "{}""#, exe.display(), config.display());
let length = line.encode_utf16().count();
if length > MAX_COMMAND_LINE {
bail!(
Expand Down
4 changes: 2 additions & 2 deletions src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ 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
/// may live in it, and they are the user's.
pub const TASK_NAME: &str = "GameModeExecutor\\Watcher";
pub const TASK_NAME: &str = r"GameModeExecutor\Watcher";

/// Whether that task is registered. `schtasks /Query` exits non-zero for a
/// task that does not exist, which is the whole answer.
Expand Down Expand Up @@ -57,7 +57,7 @@ pub fn configuration() -> Option<PathBuf> {
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}")))?
.GetFolder(&BSTR::from(format!(r"\{folder}")))?
.GetTask(&BSTR::from(name))?;
// Task Scheduler counts actions from one.
let action: IExecAction = task.Definition()?.Actions()?.get_Item(1)?.cast()?;
Expand Down
4 changes: 2 additions & 2 deletions src/win.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ pub struct SingleInstance {
impl SingleInstance {
/// Acquire the session-local mutex `name`, or fail if another process holds it.
pub fn acquire(name: &str) -> Result<Self> {
let name = HSTRING::from(format!("Local\\{name}"));
let name = HSTRING::from(format!(r"Local\{name}"));
// SAFETY: `name` is NUL-terminated and outlives the call; the handle is
// owned by `SingleInstance` and closed on drop.
let handle = unsafe { CreateMutexW(None, true, PCWSTR(name.as_ptr())) }
Expand All @@ -580,7 +580,7 @@ impl SingleInstance {
/// mutex creates nothing, and the handle is closed before returning so
/// the object does not outlive the process that owns it.
pub fn is_held(name: &str) -> bool {
let name = HSTRING::from(format!("Local\\{name}"));
let name = HSTRING::from(format!(r"Local\{name}"));
// SAFETY: `name` is NUL-terminated and outlives the call; a handle
// that comes back is closed here and kept nowhere.
match unsafe { OpenMutexW(SYNCHRONIZATION_SYNCHRONIZE, false, PCWSTR(name.as_ptr())) } {
Expand Down