Merge pull request #1575 from RobertTGreat/fix/launcher-startup-windows
🤖 Agent: merged after verify passed and the integration run on the desktop.
This commit is contained in:
@@ -122,8 +122,8 @@ pub fn locate(program: &str) -> std::path::PathBuf {
|
||||
/// Settings page's "Test the connection".
|
||||
pub fn self_test(exe: &Path) -> Result<usize, String> {
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child = Command::new(exe)
|
||||
use std::process::Stdio;
|
||||
let mut child = crate::process::command(exe)
|
||||
.arg("mcp")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -207,7 +207,7 @@ impl Launcher {
|
||||
|
||||
/// Runs a client's add command; (went well, what it said).
|
||||
fn run_add(program: &str, args: &[String]) -> (bool, String) {
|
||||
match std::process::Command::new(agents::locate(program))
|
||||
match horizon_launcher::process::command(agents::locate(program))
|
||||
.args(args)
|
||||
.output()
|
||||
{
|
||||
|
||||
+5
-10
@@ -943,7 +943,7 @@ pub fn default_minecraft_dir() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
fn found(program: &str, arg: &str) -> bool {
|
||||
Command::new(program)
|
||||
crate::process::command(program)
|
||||
.arg(arg)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
@@ -1239,14 +1239,14 @@ pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) {
|
||||
let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
|
||||
== Some(horizon_prepare::SOURCES_SHA256);
|
||||
let binary = preparer_binary(&dir).filter(|binary| {
|
||||
!own && Command::new(binary)
|
||||
!own && crate::process::command(binary)
|
||||
.arg("--help")
|
||||
.output()
|
||||
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds"))
|
||||
});
|
||||
log("Copying the sounds from your Minecraft install".into());
|
||||
let result = match binary {
|
||||
Some(binary) => Command::new(binary)
|
||||
Some(binary) => crate::process::command(binary)
|
||||
.current_dir(&dir)
|
||||
.arg("sounds")
|
||||
.arg("--root")
|
||||
@@ -1877,16 +1877,10 @@ fn parse_version_output(out: &str) -> Option<&str> {
|
||||
/// The version of the launcher binary now at `path`, which is not this process's once another
|
||||
/// update (the command line, another window) has replaced the file.
|
||||
fn installed_launcher_version(path: &Path) -> Option<String> {
|
||||
let mut cmd = Command::new(path);
|
||||
let mut cmd = crate::process::command(path);
|
||||
cmd.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
let out = cmd.output().ok()?;
|
||||
parse_version_output(&String::from_utf8_lossy(&out.stdout)).map(String::from)
|
||||
}
|
||||
@@ -2220,6 +2214,7 @@ impl Running {
|
||||
}
|
||||
|
||||
pub fn spawn(job: Job, mut cmd: Command, tx: Sender<Msg>) -> Result<Running, String> {
|
||||
crate::process::hide_console(&mut cmd);
|
||||
let mut child = cmd
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -210,7 +210,7 @@ impl Tool {
|
||||
pub fn call(&self, args: &Value) -> Result<String, String> {
|
||||
let words = self.argv(args)?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe)
|
||||
let out = horizon_launcher::process::command(exe)
|
||||
.arg("--json")
|
||||
.args(&words)
|
||||
.stdin(std::process::Stdio::null())
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! A desktop launch has no console; CLI commands can use the invoking terminal or pipes.
|
||||
#[cfg(windows)]
|
||||
pub fn attach_for_cli() -> std::io::Result<()> {
|
||||
use std::ffi::c_void;
|
||||
|
||||
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
|
||||
const STD_INPUT_HANDLE: u32 = -10_i32 as u32;
|
||||
const STD_OUTPUT_HANDLE: u32 = -11_i32 as u32;
|
||||
const STD_ERROR_HANDLE: u32 = -12_i32 as u32;
|
||||
const INVALID_HANDLE_VALUE: isize = -1;
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
extern "system" {
|
||||
fn AttachConsole(process_id: u32) -> i32;
|
||||
fn GetStdHandle(kind: u32) -> *mut c_void;
|
||||
fn SetStdHandle(kind: u32, handle: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
if std::env::args_os().nth(1).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Attaching can replace the standard handles. Keep inherited pipes/files intact for
|
||||
// JSON output, MCP and redirected logs, while filling missing handles from the terminal.
|
||||
// SAFETY: These APIs take numeric constants and opaque handles returned by Windows.
|
||||
// No handles are closed or dereferenced, and this runs before any worker starts.
|
||||
unsafe {
|
||||
let handles = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE]
|
||||
.map(|kind| (kind, GetStdHandle(kind)));
|
||||
if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
|
||||
// No parent console (for example, an MCP client), or already attached.
|
||||
return Ok(());
|
||||
}
|
||||
for (kind, handle) in handles {
|
||||
if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE {
|
||||
continue;
|
||||
}
|
||||
if SetStdHandle(kind, handle) == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn attach_for_cli() -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use horizon_launcher::backend;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Stdio};
|
||||
|
||||
pub const PREFIX: &str = "game_";
|
||||
|
||||
@@ -61,7 +61,7 @@ impl GameTools {
|
||||
if !ctl.exists() {
|
||||
return Err(format!("{tag} has no {CTL}"));
|
||||
}
|
||||
let mut child = Command::new(&ctl)
|
||||
let mut child = horizon_launcher::process::command(&ctl)
|
||||
.arg("--socket")
|
||||
.arg(socket_path())
|
||||
.arg("mcp")
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod game_app;
|
||||
pub mod heads;
|
||||
pub mod modpacks;
|
||||
pub mod mojang;
|
||||
pub mod process;
|
||||
pub mod servers;
|
||||
pub mod signed;
|
||||
pub mod sources;
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
//! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft,
|
||||
//! and starts the client or a dedicated server.
|
||||
|
||||
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
|
||||
|
||||
mod agents_page;
|
||||
mod art;
|
||||
mod blocks;
|
||||
mod cli;
|
||||
mod cli_tools;
|
||||
mod collection;
|
||||
mod console;
|
||||
mod cull;
|
||||
mod game_tools;
|
||||
mod internet;
|
||||
@@ -3517,6 +3520,10 @@ fn menus() -> Vec<Menu> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = console::attach_for_cli() {
|
||||
eprintln!("Could not restore the launcher's terminal streams: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
perf::process_started();
|
||||
backend::exe_path();
|
||||
if let Some(code) = cli::run() {
|
||||
|
||||
+89
-4
@@ -9,10 +9,11 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{self, Receiver, TryRecvError};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use horizon_bench::{App, Frames, Kind, Report};
|
||||
use horizon_bench::{App, Frames, Hardware, Kind, Report};
|
||||
|
||||
/// The first thing `main` does; every start time counts from here.
|
||||
pub fn process_started() -> Instant {
|
||||
@@ -35,14 +36,36 @@ pub struct Perf {
|
||||
dirty: bool,
|
||||
/// Off for the windows `horizon-launcher benchmark` starts: they report to it instead.
|
||||
log: bool,
|
||||
/// Machine probes run after the first frame, never while opening the window.
|
||||
hardware: Option<Receiver<Machine>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Machine {
|
||||
hardware: Hardware,
|
||||
power: Option<String>,
|
||||
load_average: Option<f64>,
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
fn detect() -> Self {
|
||||
Self {
|
||||
hardware: Hardware::detect(),
|
||||
power: horizon_bench::power_source().map(str::to_owned),
|
||||
load_average: horizon_bench::load_average(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Perf {
|
||||
pub fn new(scenario: &str) -> Perf {
|
||||
let mut report = Report::new(Kind::Launcher, app());
|
||||
let hardware = Hardware {
|
||||
os: std::env::consts::OS.to_owned(),
|
||||
arch: std::env::consts::ARCH.to_owned(),
|
||||
..Hardware::default()
|
||||
};
|
||||
let mut report = Report::with_hardware(Kind::Launcher, app(), hardware);
|
||||
report.conditions.scenario = Some(scenario.to_owned());
|
||||
report.conditions.power = horizon_bench::power_source().map(str::to_owned);
|
||||
report.conditions.load_avg_1m = horizon_bench::load_average();
|
||||
let path = crate::backend::data_dir().join("benchmarks").join(format!(
|
||||
"launcher-{}-{scenario}.json",
|
||||
report
|
||||
@@ -61,6 +84,7 @@ impl Perf {
|
||||
saved: Instant::now(),
|
||||
dirty: false,
|
||||
log: true,
|
||||
hardware: None,
|
||||
};
|
||||
if let Some(bytes) = binary_bytes() {
|
||||
perf.record("launcher.binary_bytes", bytes);
|
||||
@@ -89,6 +113,12 @@ impl Perf {
|
||||
if first {
|
||||
self.first_frame = Some(now);
|
||||
self.record_since("launcher.start_ms", process_started());
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
self.hardware = Some(receiver);
|
||||
std::thread::spawn(move || {
|
||||
// The window may close before the optional report details finish.
|
||||
let _ = sender.send(Machine::detect());
|
||||
});
|
||||
} else if let Some(gap) = self.last_frame.map(|t| now - t).filter(|g| *g < IDLE_GAP) {
|
||||
self.ui_frames.push(gap.as_secs_f32() * 1000.0);
|
||||
}
|
||||
@@ -102,6 +132,7 @@ impl Perf {
|
||||
|
||||
/// Samples memory and writes the report when something changed, at most every few seconds.
|
||||
pub fn tick(&mut self) {
|
||||
self.poll_hardware();
|
||||
if self.saved.elapsed() < Duration::from_secs(5) {
|
||||
return;
|
||||
}
|
||||
@@ -118,6 +149,7 @@ impl Perf {
|
||||
}
|
||||
|
||||
pub fn report(&mut self) -> &Report {
|
||||
self.poll_hardware();
|
||||
for (name, values) in &self.values {
|
||||
self.report.metric(name, values);
|
||||
}
|
||||
@@ -128,6 +160,24 @@ impl Perf {
|
||||
&self.report
|
||||
}
|
||||
|
||||
/// Takes the machine's details into the report once their thread has them.
|
||||
fn poll_hardware(&mut self) {
|
||||
let Some(receiver) = &self.hardware else {
|
||||
return;
|
||||
};
|
||||
match receiver.try_recv() {
|
||||
Ok(machine) => {
|
||||
self.report.hardware = machine.hardware;
|
||||
self.report.conditions.power = machine.power;
|
||||
self.report.conditions.load_avg_1m = machine.load_average;
|
||||
self.hardware = None;
|
||||
self.dirty = true;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {}
|
||||
Err(TryRecvError::Disconnected) => self.hardware = None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&mut self) {
|
||||
self.dirty = false;
|
||||
if !self.log {
|
||||
@@ -381,6 +431,41 @@ fn binary_bytes() -> Option<f64> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn performance_tracking_starts_without_hardware_probes() {
|
||||
let mut perf = Perf::new("test");
|
||||
perf.keep_local_log(false);
|
||||
assert!(perf.hardware.is_none());
|
||||
assert_eq!(perf.report.hardware.os, std::env::consts::OS);
|
||||
assert!(perf.report.hardware.cpu.is_none());
|
||||
assert!(perf.report.conditions.power.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_hardware_details_preserve_recorded_metrics() {
|
||||
let mut perf = Perf::new("test");
|
||||
perf.keep_local_log(false);
|
||||
perf.record("launcher.start_ms", 125.);
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
perf.hardware = Some(receiver);
|
||||
assert_eq!(perf.report().metrics["launcher.start_ms"].mean, 125.);
|
||||
sender
|
||||
.send(Machine {
|
||||
hardware: Hardware {
|
||||
cpu: Some("Detected CPU".into()),
|
||||
..Hardware::default()
|
||||
},
|
||||
power: Some("ac".into()),
|
||||
load_average: Some(0.5),
|
||||
})
|
||||
.unwrap();
|
||||
let report = perf.report();
|
||||
assert_eq!(report.hardware.cpu.as_deref(), Some("Detected CPU"));
|
||||
assert_eq!(report.conditions.power.as_deref(), Some("ac"));
|
||||
assert_eq!(report.metrics["launcher.start_ms"].mean, 125.);
|
||||
assert!(perf.hardware.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_frame_is_the_start_and_close_frames_are_ui_frames() {
|
||||
let mut perf = Perf::new("test");
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The programs the launcher runs in the background: on Windows they open no console window
|
||||
//! (the launcher has none to share), and keep the streams their caller gives them.
|
||||
use std::ffi::OsStr;
|
||||
use std::process::Command;
|
||||
|
||||
pub fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
hide_console(&mut command);
|
||||
command
|
||||
}
|
||||
|
||||
/// [`command`] for a `Command` made elsewhere.
|
||||
pub fn hide_console(command: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
command
|
||||
}
|
||||
@@ -245,7 +245,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = fs::remove_dir(link);
|
||||
let status = Command::new("cmd")
|
||||
let status = crate::process::command("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.arg(link)
|
||||
.arg(target)
|
||||
@@ -266,10 +266,8 @@ pub fn command(dir: &Path, args: &[&str]) -> Result<Command, String> {
|
||||
let program = program().ok_or(
|
||||
"The server programs aren't set up yet: create a server, or press Prepare on its page.",
|
||||
)?;
|
||||
let mut cmd = Command::new(program);
|
||||
let mut cmd = crate::process::command(program);
|
||||
cmd.arg("--dir").arg(dir).args(args);
|
||||
#[cfg(windows)]
|
||||
std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
@@ -752,7 +750,7 @@ pub fn lan_address() -> Option<std::net::IpAddr> {
|
||||
pub fn service_installed(dir: &Path) -> bool {
|
||||
if cfg!(windows) {
|
||||
let name = format!("horizon-server-{}", service_suffix(dir));
|
||||
return Command::new("schtasks")
|
||||
return crate::process::command("schtasks")
|
||||
.args(["/Query", "/TN", &name])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
|
||||
@@ -488,7 +488,7 @@ fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
|
||||
arg.push("\"");
|
||||
arg
|
||||
};
|
||||
let status = std::process::Command::new("cmd")
|
||||
let status = crate::process::command("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.raw_arg(quoted(link))
|
||||
.raw_arg(quoted(target))
|
||||
|
||||
@@ -126,13 +126,8 @@ pub fn status_of(cli: Option<PathBuf>) -> State {
|
||||
let Some(cli) = cli else {
|
||||
return State::Missing;
|
||||
};
|
||||
let mut command = Command::new(&cli);
|
||||
let mut command = crate::process::command(&cli);
|
||||
command.args(["status", "--json"]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
let out = match command.output() {
|
||||
Ok(out) => out,
|
||||
Err(e) => return State::Off(e.to_string()),
|
||||
|
||||
Reference in New Issue
Block a user