Skip to content
Open
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
226 changes: 226 additions & 0 deletions crates/core/src/launch_options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
//! A game's launch options, written the way Steam takes them: a command line
//! with `%command%` where the game goes, such as `~/bin/wow.sh %command%`.
//!
//! A game Lightforge starts itself is wrapped for real, outside every
//! wrapper of its own. A game Battle.net starts cannot be: the launch is a
//! message to the running client, and the game appears in the prefix with
//! nothing on the host around it. There the line runs once the game is up,
//! `%command%` standing for a command that waits for it to exit, so a script
//! that starts helpers, runs `"$@"` and cleans up after works for both.
//!
//! **Nothing here touches the game**: these are host programs around it.

use std::ffi::OsStr;
use std::io::Read;
use std::process::{Child, Command, Stdio};

use crate::preflight::GameProcess;
use crate::product::ProductCode;

/// Where the game's command goes, spelled as on Steam.
pub const PLACEHOLDER: &str = "%command%";

/// What the shell is told it is called, so its errors say who ran them:
/// `lightforge: 1: wow.sh: not found`.
const SHELL_NAME: &str = "lightforge";

/// The most of a failed line's stderr that is logged: enough for `command
/// not found` or a unit's error, not a flood.
const STDERR_KEPT: u64 = 4096;

/// The script for `sh -c`: the line with `%command%` as `"$@"`, so the
/// game's command arrives as arguments and the shell never parses it.
///
/// `None` when there is nowhere to put the game. Steam appends such a line
/// to the game's arguments, which a game Battle.net starts cannot be given.
pub fn script(line: &str) -> Option<String> {
let line = line.trim();
line.contains(PLACEHOLDER).then(|| line.replace(PLACEHOLDER, "\"$@\""))
}

/// Rebuild `cmd`, a game Lightforge starts itself, to run inside the launch
/// options. Unchanged when [`script`] has nothing.
pub fn wrap(cmd: Command, line: &str) -> Command {
let Some(script) = script(line) else {
return cmd;
};
let shell = [OsStr::new("sh"), OsStr::new("-c"), OsStr::new(&script), OsStr::new(SHELL_NAME)];
crate::tweaks::wrapped(cmd, &shell)
}

/// Start the launch options beside `game`, which Battle.net started,
/// without waiting for them. `true` when they were started.
///
/// `%command%` is `tail --pid`, which returns once the game is gone: the game
/// is no child of the shell, so `wait` cannot see it. Their exit status, and
/// what they said on stderr when they failed, go to the log.
pub fn run_beside(line: &str, product: &ProductCode, game: &GameProcess) -> bool {
let Some(script) = script(line) else {
return false;
};
tracing::info!("running the launch options for {} beside pid {}: {}", product.as_str(), game.pid, line.trim());
let mut cmd = Command::new("sh");
cmd.arg("-c")
.arg(&script)
.arg(SHELL_NAME)
.args(["tail", &format!("--pid={}", game.pid), "-f", "/dev/null"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::piped());
// Its own process group: a script's cleanup after `%command%` should
// still run when the game exits after a Ctrl+C to the launcher in its
// terminal.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
match cmd.spawn() {
Ok(child) => reap(child),
Err(e) => {
tracing::warn!("could not start the launch options for {}: {e}", product.as_str());
return false;
}
}
true
}

/// Wait for the launch options off-thread and log how they ended.
///
/// stderr is read on a thread of its own: a script that starts a daemon
/// with `&` hands it the pipe, and waiting for that to close would leave
/// the shell a zombie for as long as the daemon runs.
fn reap(mut child: Child) {
let stderr = child.stderr.take().map(|mut pipe| {
std::thread::spawn(move || {
let mut said = Vec::new();
let _ = pipe.by_ref().take(STDERR_KEPT).read_to_end(&mut said);
// Drained to the end, not dropped: the next write to a closed
// pipe is a SIGPIPE, which ended a chatty program in the line
// (a Qt app's warnings) partway through the game.
let _ = std::io::copy(&mut pipe, &mut std::io::sink());
String::from_utf8_lossy(&said).trim().to_owned()
})
});
std::thread::spawn(move || match child.wait() {
Ok(status) if status.success() => tracing::info!("the launch options finished"),
Ok(status) => {
let said = stderr.and_then(|reader| reader.join().ok()).unwrap_or_default();
match said.is_empty() {
true => tracing::warn!("the launch options failed ({status})"),
false => tracing::warn!("the launch options failed ({status}): {said}"),
}
}
Err(e) => tracing::warn!("could not wait for the launch options: {e}"),
});
}

#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};

/// A game that has already exited, so `%command%` returns at once.
fn gone() -> GameProcess {
let mut child = Command::new("true").spawn().unwrap();
child.wait().unwrap();
GameProcess { pid: child.id(), name: "Wow.exe".to_owned() }
}

fn wait_until(what: &str, done: impl Fn() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !done() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
assert!(done(), "{what}");
}

#[test]
fn a_line_without_the_placeholder_runs_nothing() {
assert_eq!(script(" "), None);
assert_eq!(script("gamemoderun"), None, "nowhere to put the game");
assert!(!run_beside("gamemoderun", &ProductCode::Retail, &gone()));
assert_eq!(wrap(Command::new("/proton/proton"), "gamemoderun").get_program(), "/proton/proton");
}

// The shell never reads the game's command as text, so nothing in it is
// expanded, split or taken for the placeholder.
#[test]
fn the_game_command_arrives_untouched() {
let mut game = Command::new("printf");
game.args(["%s|", "two words", "$HOME", "it's", "%command%"]);
let out = wrap(game, "env LIGHTFORGE_TEST=1 %command% --last").output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), "two words|$HOME|it's|%command%|--last|");
}

// Proton finds the prefix through the environment, and a launch may set
// the folder it runs in: both have to reach the game through the shell.
#[test]
fn the_wrapped_game_keeps_its_environment_and_folder() {
let dir = tempfile::tempdir().unwrap();
let mut game = Command::new("sh");
game.arg("-c").arg("printf '%s|%s' \"$STEAM_COMPAT_DATA_PATH\" \"$(pwd)\"");
game.env("STEAM_COMPAT_DATA_PATH", "/compat").current_dir(dir.path());
let out = wrap(game, "%command%").output().unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout), format!("/compat|{}", dir.path().display()));
}

// The shape of a Steam user's script: helpers up, the game, helpers down.
#[test]
fn a_script_runs_around_a_wrapped_game() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let mut game = Command::new("sh");
game.arg("-c").arg(format!("echo game >> '{}'", log.display()));
let line = format!("echo up >> '{0}'; %command%; echo down >> '{0}'", log.display());
assert!(wrap(game, &line).status().unwrap().success());
assert_eq!(std::fs::read_to_string(&log).unwrap(), "up\ngame\ndown\n");
}

// Beside a game Battle.net started, `%command%` lasts as long as the
// game, and the caller does not wait for any of it.
#[test]
fn beside_a_running_game_the_command_lasts_until_it_exits() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("log");
let read = || std::fs::read_to_string(&log).unwrap_or_default();
let mut stand_in = Command::new("sleep").arg("30").spawn().unwrap();
let game = GameProcess { pid: stand_in.id(), name: "Wow.exe".to_owned() };

let line = format!("echo up >> '{0}'; %command%; echo down >> '{0}'", log.display());
assert!(run_beside(&line, &ProductCode::Retail, &game));
wait_until("the line started", || read() == "up\n");
// Longer than `tail --pid` takes to notice a game that is gone.
std::thread::sleep(Duration::from_millis(1500));
assert_eq!(read(), "up\n", "nothing after %command% while the game runs");

stand_in.kill().unwrap();
// Reaped, as Wine reaps the real game: `tail` sees a zombie as alive.
stand_in.wait().unwrap();
wait_until("the cleanup ran after the game exited", || read() == "up\ndown\n");
}

// A program started in the line runs for the whole session, and may say
// far more on stderr than the log keeps. The shell writes 220 KB itself,
// past the pipe's 64 KiB buffer, and only reaches the file if no write
// was cut off.
#[test]
fn a_line_that_says_more_than_the_log_keeps_is_not_cut_off() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("done");
let line = format!(
"i=0; while [ $i -lt 20000 ]; do printf 'xxxxxxxxxx\\n' >&2; i=$((i+1)); done; echo done > '{}'; %command%",
out.display()
);
assert!(run_beside(&line, &ProductCode::Retail, &gone()));
wait_until("the line was killed before it finished", || out.exists());
}

#[test]
fn a_profile_without_launch_options_saves_as_it_was() {
let old: crate::product::ProductProfile = toml::from_str("proton_ge_version = \"GE-Proton10-1\"").unwrap();
assert!(old.launch_options.is_empty());
let saved = toml::to_string(&old).unwrap();
assert!(!saved.contains("launch_options"), "{saved}");
}
}
1 change: 1 addition & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod families;
pub(crate) mod fsutil;
#[cfg(fuzzing)]
pub mod fuzzing;
pub mod launch_options;
pub mod library;
pub mod logging;
pub mod migrate;
Expand Down
4 changes: 4 additions & 0 deletions crates/core/src/product.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,10 @@ pub struct ProductProfile {
pub cdn_override: Option<String>,
/// Launch settings for this product: wrappers and environment.
pub tweaks: crate::tweaks::Tweaks,
/// Steam-style launch options, `%command%` where the game goes; see
/// [`crate::launch_options`]. Empty for none.
#[serde(skip_serializing_if = "String::is_empty")]
pub launch_options: String,
/// Optional content opted in to, by tag name, e.g. `HighRes`.
pub optional_content: Vec<String>,
/// What the last plan said this product offers: a cache, not a setting.
Expand Down
12 changes: 6 additions & 6 deletions crates/core/src/tweaks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
//! wrapper and environment variables.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;

Expand Down Expand Up @@ -257,10 +257,11 @@ fn is_executable(path: &Path) -> bool {
path.is_file()
}

/// Rebuild `cmd` to run under `wrappers`, outermost first.
/// Rebuild `cmd` to run under `wrappers`, outermost first: programs, or a
/// program and its arguments, as `sh -c <script>` is for the launch options.
///
/// [`Command`] cannot be wrapped in place, so it is rebuilt.
pub fn wrapped(cmd: Command, wrappers: &[PathBuf]) -> Command {
pub fn wrapped(cmd: Command, wrappers: &[impl AsRef<OsStr>]) -> Command {
let Some((outer, rest)) = wrappers.split_first() else {
return cmd;
};
Expand All @@ -286,7 +287,6 @@ pub fn wrapped(cmd: Command, wrappers: &[PathBuf]) -> Command {
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsStr;

#[test]
fn a_default_profile_asks_for_nothing() {
Expand Down Expand Up @@ -429,7 +429,7 @@ mod tests {
let mut inner = Command::new("/proton/proton");
inner.arg("run").arg("/games/Wow.exe").env("STEAM_COMPAT_DATA_PATH", "/compat");

let outer = wrapped(inner, &["/usr/bin/game-performance".into()]);
let outer = wrapped(inner, &["/usr/bin/game-performance"]);
assert_eq!(outer.get_program(), "/usr/bin/game-performance");
let args: Vec<_> = outer.get_args().collect();
assert_eq!(args, ["/proton/proton", "run", "/games/Wow.exe"]);
Expand All @@ -442,7 +442,7 @@ mod tests {
fn no_wrappers_leaves_the_command_untouched() {
let mut inner = Command::new("/proton/proton");
inner.arg("run");
let outer = wrapped(inner, &[]);
let outer = wrapped(inner, &[] as &[PathBuf]);
assert_eq!(outer.get_program(), "/proton/proton");
}

Expand Down
14 changes: 9 additions & 5 deletions crates/launcher-cli/src/commands/play.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ pub(crate) fn play(ctx: Ctx, code: ProductCode, proton: Option<String>, dry_run:

// The same per-product settings Game Settings writes. A launcher that honoured them from one entry point and
// not the other would make every measurement unreproducible.
let tweaks = Config::load_or_default(&dirs.config_file())
let profile = Config::load_or_default(&dirs.config_file())
.ok()
.and_then(|config| config.product(&code).map(|p| p.profile.tweaks.clone()))
.and_then(|config| config.product(&code).map(|p| p.profile.clone()))
.unwrap_or_default();
let tweaks = &profile.tweaks;
let tools = lightforge_core::tweaks::HostTools::detect();
for (key, value) in tweaks.environment(&tools) {
runner = runner.with_env(key, value);
Expand All @@ -50,6 +51,9 @@ pub(crate) fn play(ctx: Ctx, code: ProductCode, proton: Option<String>, dry_run:
wrappers.iter().map(|w| w.display().to_string()).collect();
println!("through {}", names.join(" "));
}
if lightforge_core::launch_options::script(&profile.launch_options).is_some() {
println!("options {}", profile.launch_options.trim());
}
if dry_run {
return Ok(());
}
Expand All @@ -61,9 +65,9 @@ pub(crate) fn play(ctx: Ctx, code: ProductCode, proton: Option<String>, dry_run:
.context("pre-flight cleanup")?;
print_preflight(&report);

let status = lightforge_core::tweaks::wrapped(
runner.command("run", &exe, Vec::<String>::new()),
&wrappers,
let status = lightforge_core::launch_options::wrap(
lightforge_core::tweaks::wrapped(runner.command("run", &exe, Vec::<String>::new()), &wrappers),
&profile.launch_options,
)
.status()
.context("launching the game")?;
Expand Down
5 changes: 3 additions & 2 deletions crates/launcher-gui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,9 +477,10 @@ struct Lightforge {
/// The environment-variable editors: Game Settings' and Battle.net's.
env_editor: iced::widget::text_editor::Content,
bnet_env_editor: iced::widget::text_editor::Content,
/// Counts env edits, so only the save scheduled by the last one runs.
/// Counts typed edits, of the environment or the launch options, so only
/// the save scheduled by the last one runs.
env_edits: u64,
/// An env edit is in the config but not yet on disk.
/// A typed edit is in the config but not yet on disk.
env_unsaved: bool,
/// Editable copies of the selected product's numeric tweaks, and the two
/// fields of the environment escape hatch.
Expand Down
5 changes: 4 additions & 1 deletion crates/launcher-gui/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,11 @@ pub(crate) enum Message {
Tweak(Scope, Tweak, bool),
/// The environment-variable editor was typed in.
EnvEdit(Scope, iced::widget::text_editor::Action),
/// Typing in the env editor paused; the number says after which edit.
/// Typing in the env editor or the launch options paused; the number says
/// after which edit.
EnvSettled(u64),
/// The launch options in Game Settings were typed in.
LaunchOptionsTyped(String),
/// Typing in the folder to move the Wine prefix to.
PrefixFolderTyped(String),
BrowsePrefixFolder,
Expand Down
20 changes: 16 additions & 4 deletions crates/launcher-gui/src/tasks/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,17 @@ pub async fn start_game(layout: Layout, code: ProductCode) -> Result<Started, Pr

back_up_before_launch(&layout, &code);

let (tweaks, tools) = tweaks_for(&code);
let (profile, tools) = profile_for(&code);

let runner = runner_for(&layout, &code, Runs::Game)?;
let mut launch = lightforge_core::tweaks::wrapped(
runner.command("run", &exe, Vec::<String>::new()),
&tweaks.wrappers(&tools),
// The user's launch options outermost, as Steam puts them: around
// every wrapper of our own.
let mut launch = lightforge_core::launch_options::wrap(
lightforge_core::tweaks::wrapped(
runner.command("run", &exe, Vec::<String>::new()),
&profile.tweaks.wrappers(&tools),
),
&profile.launch_options,
);

let generation =
Expand Down Expand Up @@ -464,6 +469,13 @@ pub(crate) const KEEP_IN_TRAY: Duration = Duration::from_secs(8);
/// claiming a launch is in progress.
pub(crate) const HANDOFF_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(180);

/// Start a game's launch options beside it, for a game Battle.net started.
///
/// Never fails a launch: launch options that cannot start are only logged.
pub async fn run_beside(line: String, code: ProductCode, game: GameProcess) {
let _ = tokio::task::spawn_blocking(move || lightforge_core::launch_options::run_beside(&line, &code, &game)).await;
}

/// Block until a game exits, by pid: a title that re-execs itself ends the
/// session early instead of hanging.
///
Expand Down
Loading