From 80eacf9ac282653184facf9064f2dfa3f51bd0ff Mon Sep 17 00:00:00 2001 From: Arths17 Date: Wed, 25 Nov 2026 14:33:22 -0600 Subject: [PATCH] Add the betterxen-hybrid crate: host receipt, CrossOver discovery, toolchain probe and frame statistics --- CHANGELOG.md | 2 + Cargo.lock | 30 +++--- crates/hybrid/Cargo.toml | 14 +++ crates/hybrid/src/cmdutil.rs | 13 +++ crates/hybrid/src/crossover.rs | 162 ++++++++++++++++++++++++++++ crates/hybrid/src/frames.rs | 192 +++++++++++++++++++++++++++++++++ crates/hybrid/src/host.rs | 140 ++++++++++++++++++++++++ crates/hybrid/src/json.rs | 114 ++++++++++++++++++++ crates/hybrid/src/lib.rs | 30 ++++++ crates/hybrid/src/main.rs | 99 +++++++++++++++++ crates/hybrid/src/toolchain.rs | 82 ++++++++++++++ 11 files changed, 865 insertions(+), 13 deletions(-) create mode 100644 crates/hybrid/Cargo.toml create mode 100644 crates/hybrid/src/cmdutil.rs create mode 100644 crates/hybrid/src/crossover.rs create mode 100644 crates/hybrid/src/frames.rs create mode 100644 crates/hybrid/src/host.rs create mode 100644 crates/hybrid/src/json.rs create mode 100644 crates/hybrid/src/lib.rs create mode 100644 crates/hybrid/src/main.rs create mode 100644 crates/hybrid/src/toolchain.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ef7bb8..bb83011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- Added the `betterxen-hybrid` crate (`crates/hybrid`, no third-party dependencies, native arm64) with `host`, `crossover`, `toolchain`, `frames` and `receipt` commands that print JSON: a host receipt (macOS, chip, memory, core split, whether an x86_64 binary runs under Rosetta, GPU and Metal family), CrossOver discovery limited to `Info.plist` metadata, `lipo -archs` and the documented `BottleDir` and `ManagedBottleDirs` preferences, a Windows cross-compiler probe, and frame-time statistics (nearest-rank percentiles, 1 % and 0.1 % lows, stutter count). Locally verified: 13 unit tests, clippy with warnings denied, and a run on the Apple M4 reference machine, where CrossOver is **not installed** (the report says so) and only Homebrew mingw-w64 x86_64 and i686 compilers were found. CrossOver discovery has been tested on a synthetic bundle only and has never inspected a real CrossOver; nothing launches a program or measures a game. Not independently reviewed (#353, #350, #364, #145). +- Added `docs/research/upstream-integration-audit.md` and registry and reuse-matrix rows for skakwy/victory-mac, MacBox, ScarlettMac, ossover, Whisky and rum (source read through the GitHub API, nothing executed, no code copied). Findings: MacBox and ScarlettMac are GPL-2.0 and game-specific, so they are rejected; the Game Porting Toolkit licence text (a third-party copy of version 4.0) limits use to developing, testing or evaluating games and distribution to non-commercial; contributor-reported frame results (about 1 FPS, then two rendered frames) are recorded as unverified. - Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346). - Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run. - Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed. diff --git a/Cargo.lock b/Cargo.lock index f52ddd9..468797a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,23 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "betterxen" +version = "0.1.0" +dependencies = [ + "xenora-decoder", + "xenora-import-gen", + "xenora-isa", + "xenora-loader", + "xenora-metal", + "xenora-ref", + "xenora-shader", +] + +[[package]] +name = "betterxen-hybrid" +version = "0.1.0" + [[package]] name = "bitflags" version = "2.13.2" @@ -149,19 +166,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "betterxen" -version = "0.1.0" -dependencies = [ - "xenora-decoder", - "xenora-import-gen", - "xenora-isa", - "xenora-loader", - "xenora-metal", - "xenora-ref", - "xenora-shader", -] - [[package]] name = "xenora-benchmarks" version = "0.1.0" diff --git a/crates/hybrid/Cargo.toml b/crates/hybrid/Cargo.toml new file mode 100644 index 0000000..cc77d4c --- /dev/null +++ b/crates/hybrid/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "betterxen-hybrid" +description = "Host receipt, CrossOver discovery, frame-time statistics and Windows cross-toolchain probes for the hybrid direction" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[[bin]] +name = "betterxen-hybrid" +path = "src/main.rs" diff --git a/crates/hybrid/src/cmdutil.rs b/crates/hybrid/src/cmdutil.rs new file mode 100644 index 0000000..156ee7c --- /dev/null +++ b/crates/hybrid/src/cmdutil.rs @@ -0,0 +1,13 @@ +//! Run a system tool and capture trimmed stdout. A missing tool or non-zero exit is `None`, +//! never a guessed value. + +use std::process::Command; + +pub fn run(program: &str, args: &[&str]) -> Option { + let out = Command::new(program).args(args).output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); + Some(s) +} diff --git a/crates/hybrid/src/crossover.rs b/crates/hybrid/src/crossover.rs new file mode 100644 index 0000000..84f47ad --- /dev/null +++ b/crates/hybrid/src/crossover.rs @@ -0,0 +1,162 @@ +//! Discover installed CrossOver bundles and read standard bundle metadata. +//! +//! Only documented or standard macOS interfaces are used: the app bundle's `Info.plist` +//! (read through `plutil`), `lipo -archs` on the bundle's main executable, and the +//! `defaults` keys CodeWeavers documents in "Advanced CrossOver Mac Configuration" +//! (`BottleDir`, `ManagedBottleDirs` in `com.codeweavers.CrossOver`). Bundle internals such +//! as `Contents/SharedSupport` are NOT interpreted: they are undocumented and not a stable +//! interface (#350). The graphics backend of a bottle is deliberately not read. + +use crate::cmdutil::run; +use crate::json::Json; +use std::path::{Path, PathBuf}; + +pub const BUNDLE_ID: &str = "com.codeweavers.CrossOver"; + +#[derive(Debug, Clone, PartialEq)] +pub struct Install { + pub path: PathBuf, + pub bundle_id: Option, + pub short_version: Option, + pub build_version: Option, + pub executable_archs: Option>, + pub minimum_macos: Option, +} + +/// Candidate bundle locations: standard application directories. Spotlight is consulted too. +pub fn candidate_paths(home: &Path) -> Vec { + let mut v = vec![ + PathBuf::from("/Applications/CrossOver.app"), + home.join("Applications/CrossOver.app"), + ]; + if let Some(found) = run( + "/usr/bin/mdfind", + &[&format!("kMDItemCFBundleIdentifier == '{BUNDLE_ID}'")], + ) { + for line in found.lines().filter(|l| !l.is_empty()) { + let p = PathBuf::from(line); + if !v.contains(&p) { + v.push(p); + } + } + } + v +} + +pub fn discover(candidates: &[PathBuf]) -> Vec { + candidates.iter().filter_map(|p| inspect(p)).collect() +} + +/// Inspect one bundle. Returns None if the path has no readable `Contents/Info.plist`. +pub fn inspect(app: &Path) -> Option { + let plist = app.join("Contents/Info.plist"); + if !plist.is_file() { + return None; + } + let json = run( + "/usr/bin/plutil", + &["-convert", "json", "-o", "-", plist.to_str()?], + )?; + let exe = crate::host_string(&json, "CFBundleExecutable"); + let archs = exe.and_then(|e| { + let p = app.join("Contents/MacOS").join(e); + run("/usr/bin/lipo", &["-archs", p.to_str()?]) + .map(|s| s.split_whitespace().map(String::from).collect()) + }); + Some(Install { + path: app.to_path_buf(), + bundle_id: crate::host_string(&json, "CFBundleIdentifier"), + short_version: crate::host_string(&json, "CFBundleShortVersionString"), + build_version: crate::host_string(&json, "CFBundleVersion"), + executable_archs: archs, + minimum_macos: crate::host_string(&json, "LSMinimumSystemVersion"), + }) +} + +/// A documented CrossOver preference, or None when unset or unreadable. +pub fn preference(key: &str) -> Option { + run("/usr/bin/defaults", &["read", BUNDLE_ID, key]) +} + +impl Install { + pub fn to_json(&self) -> Json { + Json::obj(vec![ + ("path", Json::str(self.path.display().to_string())), + ("bundle_id", Json::opt_str(self.bundle_id.clone())), + ("short_version", Json::opt_str(self.short_version.clone())), + ("build_version", Json::opt_str(self.build_version.clone())), + ( + "executable_archs", + self.executable_archs.as_ref().map_or(Json::Null, |a| { + Json::Arr(a.iter().map(|s| Json::str(s.clone())).collect()) + }), + ), + ("minimum_macos", Json::opt_str(self.minimum_macos.clone())), + ( + "bundle_id_is_codeweavers_crossover", + Json::Bool(self.bundle_id.as_deref() == Some(BUNDLE_ID)), + ), + ]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + // A synthetic bundle written by the test: it proves the metadata path, not that + // any real CrossOver build has this layout. + fn fake_bundle(dir: &Path) -> PathBuf { + let app = dir.join("CrossOver.app"); + fs::create_dir_all(app.join("Contents/MacOS")).unwrap(); + fs::write( + app.join("Contents/Info.plist"), + r#" + + +CFBundleExecutableCrossOver +CFBundleIdentifiercom.codeweavers.CrossOver +CFBundleShortVersionString99.1.2 +CFBundleVersion12345 +LSMinimumSystemVersion14.0 +"#, + ) + .unwrap(); + // Copy a real system executable so `lipo -archs` has a Mach-O to read. + fs::copy("/usr/bin/true", app.join("Contents/MacOS/CrossOver")).unwrap(); + app + } + + #[test] + fn reads_bundle_metadata() { + if !cfg!(target_os = "macos") { + return; + } + let tmp = std::env::temp_dir().join(format!("bxhybrid-co-{}", std::process::id())); + let _ = fs::remove_dir_all(&tmp); + fs::create_dir_all(&tmp).unwrap(); + let app = fake_bundle(&tmp); + let i = inspect(&app).expect("inspect"); + assert_eq!(i.short_version.as_deref(), Some("99.1.2")); + assert_eq!(i.build_version.as_deref(), Some("12345")); + assert_eq!(i.minimum_macos.as_deref(), Some("14.0")); + assert_eq!(i.bundle_id.as_deref(), Some(BUNDLE_ID)); + assert!( + i.executable_archs.as_ref().is_some_and(|a| !a.is_empty()), + "{:?}", + i.executable_archs + ); + assert_eq!(discover(&[app.clone(), tmp.join("Missing.app")]).len(), 1); + fs::remove_dir_all(&tmp).unwrap(); + } + + #[test] + fn missing_or_plistless_bundle_is_none() { + let tmp = std::env::temp_dir().join(format!("bxhybrid-co2-{}", std::process::id())); + fs::create_dir_all(tmp.join("X.app/Contents")).unwrap(); + assert!(inspect(&tmp.join("X.app")).is_none()); + assert!(inspect(&tmp.join("Nope.app")).is_none()); + fs::remove_dir_all(&tmp).unwrap(); + } +} diff --git a/crates/hybrid/src/frames.rs b/crates/hybrid/src/frames.rs new file mode 100644 index 0000000..a09d6fd --- /dev/null +++ b/crates/hybrid/src/frames.rs @@ -0,0 +1,192 @@ +//! Frame-time statistics from a list of frame intervals in milliseconds (issue #145). +//! +//! Percentiles use the nearest-rank method on the sorted intervals: the p-th percentile is +//! the value at rank ceil(p/100 * n) (1-based). "1 % low FPS" is 1000 divided by the 99th +//! percentile interval. These definitions are fixed here so reports are comparable; other +//! tools define lows differently (for example as the mean of the worst 1 %). + +use crate::json::Json; + +#[derive(Debug, Clone, PartialEq)] +pub struct FrameStats { + pub frames: usize, + pub total_ms: f64, + pub mean_ms: f64, + pub avg_fps: f64, + pub min_ms: f64, + pub max_ms: f64, + pub p50_ms: f64, + pub p95_ms: f64, + pub p99_ms: f64, + pub p999_ms: f64, + pub low_1pct_fps: f64, + pub low_01pct_fps: f64, + /// Frames longer than twice the median interval. + pub stutters: usize, +} + +#[derive(Debug, PartialEq)] +pub enum FrameError { + Empty, + Invalid { index: usize, value: f64 }, + Parse { line: usize, text: String }, +} + +impl std::fmt::Display for FrameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + FrameError::Empty => write!(f, "no frame intervals"), + FrameError::Invalid { index, value } => { + write!( + f, + "frame {index}: interval {value} is not a positive finite number of milliseconds" + ) + } + FrameError::Parse { line, text } => { + write!(f, "line {line}: cannot parse {text:?} as milliseconds") + } + } + } +} + +impl std::error::Error for FrameError {} + +fn nearest_rank(sorted: &[f64], pct: f64) -> f64 { + let n = sorted.len(); + let rank = ((pct / 100.0) * n as f64).ceil().max(1.0) as usize; + sorted[rank.min(n) - 1] +} + +pub fn analyze(intervals_ms: &[f64]) -> Result { + if intervals_ms.is_empty() { + return Err(FrameError::Empty); + } + for (index, &value) in intervals_ms.iter().enumerate() { + if !value.is_finite() || value <= 0.0 { + return Err(FrameError::Invalid { index, value }); + } + } + let mut sorted = intervals_ms.to_vec(); + sorted.sort_by(|a, b| a.total_cmp(b)); + let total: f64 = intervals_ms.iter().sum(); + let n = sorted.len(); + let p50 = nearest_rank(&sorted, 50.0); + let p99 = nearest_rank(&sorted, 99.0); + let p999 = nearest_rank(&sorted, 99.9); + Ok(FrameStats { + frames: n, + total_ms: total, + mean_ms: total / n as f64, + avg_fps: n as f64 / (total / 1000.0), + min_ms: sorted[0], + max_ms: sorted[n - 1], + p50_ms: p50, + p95_ms: nearest_rank(&sorted, 95.0), + p99_ms: p99, + p999_ms: p999, + low_1pct_fps: 1000.0 / p99, + low_01pct_fps: 1000.0 / p999, + stutters: intervals_ms.iter().filter(|&&v| v > 2.0 * p50).count(), + }) +} + +/// Parse one interval per line; blank lines and lines starting with `#` are skipped. +pub fn parse_intervals(text: &str) -> Result, FrameError> { + let mut out = Vec::new(); + for (i, line) in text.lines().enumerate() { + let t = line.trim(); + if t.is_empty() || t.starts_with('#') { + continue; + } + let v: f64 = t.parse().map_err(|_| FrameError::Parse { + line: i + 1, + text: t.to_string(), + })?; + out.push(v); + } + Ok(out) +} + +impl FrameStats { + pub fn to_json(&self) -> Json { + Json::obj(vec![ + ("frames", Json::Num(self.frames as f64)), + ("total_ms", Json::Num(self.total_ms)), + ("mean_ms", Json::Num(self.mean_ms)), + ("avg_fps", Json::Num(self.avg_fps)), + ("min_ms", Json::Num(self.min_ms)), + ("max_ms", Json::Num(self.max_ms)), + ("p50_ms", Json::Num(self.p50_ms)), + ("p95_ms", Json::Num(self.p95_ms)), + ("p99_ms", Json::Num(self.p99_ms)), + ("p999_ms", Json::Num(self.p999_ms)), + ("low_1pct_fps", Json::Num(self.low_1pct_fps)), + ("low_0_1pct_fps", Json::Num(self.low_01pct_fps)), + ("stutters_over_2x_median", Json::Num(self.stutters as f64)), + ("percentile_method", Json::str("nearest-rank")), + ]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Expected values below are worked out by hand, not produced by analyze(). + #[test] + fn known_answer_ten_frames() { + // Sorted: 10,10,10,10,10,10,10,10,20,100. Total 200 ms, n = 10. + let v = [10.0, 10.0, 10.0, 10.0, 20.0, 10.0, 10.0, 10.0, 100.0, 10.0]; + let s = analyze(&v).unwrap(); + assert_eq!(s.frames, 10); + assert_eq!(s.total_ms, 200.0); + assert_eq!(s.mean_ms, 20.0); + assert_eq!(s.avg_fps, 50.0); + assert_eq!(s.p50_ms, 10.0); // rank 5 + assert_eq!(s.p95_ms, 100.0); // rank ceil(9.5) = 10 + assert_eq!(s.p99_ms, 100.0); + assert_eq!(s.low_1pct_fps, 10.0); + assert_eq!(s.stutters, 1); // threshold is 2 * 10 = 20; 20 is not > 20, only 100 is. + } + + #[test] + fn stutter_threshold_is_strict() { + let s = analyze(&[10.0, 10.0, 10.0, 20.0, 21.0]).unwrap(); + assert_eq!(s.stutters, 1); + } + + #[test] + fn one_frame_per_second() { + let s = analyze(&[1000.0, 1000.0]).unwrap(); + assert_eq!(s.avg_fps, 1.0); + } + + #[test] + fn rejects_bad_input() { + assert_eq!(analyze(&[]), Err(FrameError::Empty)); + assert!(matches!( + analyze(&[1.0, 0.0]), + Err(FrameError::Invalid { index: 1, .. }) + )); + assert!(matches!( + analyze(&[f64::NAN]), + Err(FrameError::Invalid { .. }) + )); + assert!(matches!(analyze(&[-3.0]), Err(FrameError::Invalid { .. }))); + } + + #[test] + fn parses_text() { + assert_eq!( + parse_intervals("# c\n16.5\n\n 8 \n").unwrap(), + vec![16.5, 8.0] + ); + assert_eq!( + parse_intervals("1\nabc\n"), + Err(FrameError::Parse { + line: 2, + text: "abc".into() + }) + ); + } +} diff --git a/crates/hybrid/src/host.rs b/crates/hybrid/src/host.rs new file mode 100644 index 0000000..d2678a6 --- /dev/null +++ b/crates/hybrid/src/host.rs @@ -0,0 +1,140 @@ +//! Host receipt: what this Mac is, from documented system interfaces (issue #353). +//! +//! Every field is `Option` where the probe can fail; absence is reported as null, not guessed. + +use crate::cmdutil::run; +use crate::json::Json; + +#[derive(Debug, Clone, PartialEq)] +pub struct HostReceipt { + pub macos_version: Option, + pub macos_build: Option, + pub chip: Option, + pub apple_silicon: Option, + pub memory_bytes: Option, + pub logical_cpus: Option, + pub performance_cores: Option, + pub efficiency_cores: Option, + /// True only if an x86_64 slice of a system binary actually executed. + pub rosetta_executes_x86_64: Option, + pub gpu_name: Option, + pub gpu_cores: Option, + pub metal_support: Option, + pub host_arch_of_this_binary: &'static str, +} + +fn sysctl(name: &str) -> Option { + run("/usr/sbin/sysctl", &["-n", name]) +} + +pub fn collect() -> HostReceipt { + let gpu = run( + "/usr/sbin/system_profiler", + &["SPDisplaysDataType", "-json"], + ) + .and_then(|j| parse_gpu(&j)); + HostReceipt { + macos_version: run("/usr/bin/sw_vers", &["-productVersion"]), + macos_build: sysctl("kern.osversion"), + chip: sysctl("machdep.cpu.brand_string"), + apple_silicon: sysctl("hw.optional.arm64").map(|v| v == "1"), + memory_bytes: sysctl("hw.memsize").and_then(|v| v.parse().ok()), + logical_cpus: sysctl("hw.logicalcpu").and_then(|v| v.parse().ok()), + performance_cores: sysctl("hw.perflevel0.physicalcpu").and_then(|v| v.parse().ok()), + efficiency_cores: sysctl("hw.perflevel1.physicalcpu").and_then(|v| v.parse().ok()), + // Executes the x86_64 slice of /usr/bin/true. Failure means Rosetta cannot run it + // now; it does not distinguish "not installed" from "disabled". + rosetta_executes_x86_64: Some( + run("/usr/bin/arch", &["-x86_64", "/usr/bin/true"]).is_some(), + ), + gpu_name: gpu.as_ref().map(|g| g.0.clone()), + gpu_cores: gpu.as_ref().and_then(|g| g.1.clone()), + metal_support: gpu.as_ref().and_then(|g| g.2.clone()), + host_arch_of_this_binary: std::env::consts::ARCH, + } +} + +/// Pull `sppci_model`, `sppci_cores` and `spdisplays_mtlgpufamilysupport` of the first display +/// entry from `system_profiler SPDisplaysDataType -json` output. Returns None if the model +/// key is absent. Uses a small string scan because this crate has no JSON parser dependency. +pub fn parse_gpu(json: &str) -> Option<(String, Option, Option)> { + let model = string_value(json, "sppci_model")?; + Some(( + model, + string_value(json, "sppci_cores"), + string_value(json, "spdisplays_mtlgpufamilysupport"), + )) +} + +fn string_value(json: &str, key: &str) -> Option { + let needle = format!("\"{key}\""); + let at = json.find(&needle)? + needle.len(); + let rest = json[at..].trim_start().strip_prefix(':')?.trim_start(); + let rest = rest.strip_prefix('"')?; + let end = rest.find('"')?; + Some(rest[..end].to_string()) +} + +impl HostReceipt { + pub fn to_json(&self) -> Json { + let n = |v: Option| v.map_or(Json::Null, |x| Json::Num(x as f64)); + Json::obj(vec![ + ("macos_version", Json::opt_str(self.macos_version.clone())), + ("macos_build", Json::opt_str(self.macos_build.clone())), + ("chip", Json::opt_str(self.chip.clone())), + ( + "apple_silicon", + self.apple_silicon.map_or(Json::Null, Json::Bool), + ), + ( + "memory_bytes", + self.memory_bytes + .map_or(Json::Null, |x| Json::Num(x as f64)), + ), + ("logical_cpus", n(self.logical_cpus)), + ("performance_cores", n(self.performance_cores)), + ("efficiency_cores", n(self.efficiency_cores)), + ( + "rosetta_executes_x86_64", + self.rosetta_executes_x86_64.map_or(Json::Null, Json::Bool), + ), + ("gpu_name", Json::opt_str(self.gpu_name.clone())), + ("gpu_cores", Json::opt_str(self.gpu_cores.clone())), + ("metal_support", Json::opt_str(self.metal_support.clone())), + ( + "receipt_binary_arch", + Json::str(self.host_arch_of_this_binary), + ), + ]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_gpu_fixture() { + let j = r#"{"SPDisplaysDataType":[{"sppci_cores":"10","sppci_model":"Apple M4", + "spdisplays_mtlgpufamilysupport":"spdisplays_metal4"}]}"#; + let g = parse_gpu(j).unwrap(); + assert_eq!(g.0, "Apple M4"); + assert_eq!(g.1.as_deref(), Some("10")); + assert_eq!(g.2.as_deref(), Some("spdisplays_metal4")); + } + + #[test] + fn missing_gpu_is_none() { + assert!(parse_gpu("{}").is_none()); + } + + #[test] + fn collect_runs_on_this_host() { + let r = collect(); + if cfg!(target_os = "macos") { + assert!(r.macos_version.is_some()); + assert!(r.memory_bytes.unwrap() > 0); + } + assert!(r.to_json().render().contains("receipt_binary_arch")); + } +} diff --git a/crates/hybrid/src/json.rs b/crates/hybrid/src/json.rs new file mode 100644 index 0000000..10cb1b2 --- /dev/null +++ b/crates/hybrid/src/json.rs @@ -0,0 +1,114 @@ +//! Minimal JSON value and writer. Output only; no parsing is needed by this crate. + +#[derive(Debug, Clone, PartialEq)] +pub enum Json { + Null, + Bool(bool), + Num(f64), + Str(String), + Arr(Vec), + Obj(Vec<(String, Json)>), +} + +impl Json { + pub fn str(s: impl Into) -> Json { + Json::Str(s.into()) + } + pub fn opt_str(s: Option) -> Json { + s.map_or(Json::Null, Json::Str) + } + pub fn obj(fields: Vec<(&str, Json)>) -> Json { + Json::Obj( + fields + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(), + ) + } + + pub fn render(&self) -> String { + let mut out = String::new(); + self.write(&mut out, 0); + out.push('\n'); + out + } + + fn write(&self, out: &mut String, depth: usize) { + let pad = |out: &mut String, d: usize| out.push_str(&" ".repeat(d)); + match self { + Json::Null => out.push_str("null"), + Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }), + Json::Num(n) if n.is_finite() => { + if n.fract() == 0.0 && n.abs() < 1e15 { + out.push_str(&format!("{}", *n as i64)); + } else { + out.push_str(&format!("{n}")); + } + } + // JSON has no NaN or infinity; refuse to invent a number. + Json::Num(_) => out.push_str("null"), + Json::Str(s) => escape(s, out), + Json::Arr(items) if items.is_empty() => out.push_str("[]"), + Json::Arr(items) => { + out.push_str("[\n"); + for (i, item) in items.iter().enumerate() { + pad(out, depth + 1); + item.write(out, depth + 1); + out.push_str(if i + 1 < items.len() { ",\n" } else { "\n" }); + } + pad(out, depth); + out.push(']'); + } + Json::Obj(fields) if fields.is_empty() => out.push_str("{}"), + Json::Obj(fields) => { + out.push_str("{\n"); + for (i, (k, v)) in fields.iter().enumerate() { + pad(out, depth + 1); + escape(k, out); + out.push_str(": "); + v.write(out, depth + 1); + out.push_str(if i + 1 < fields.len() { ",\n" } else { "\n" }); + } + pad(out, depth); + out.push('}'); + } + } + } +} + +fn escape(s: &str, out: &mut String) { + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escapes_and_nests() { + let j = Json::obj(vec![ + ("a", Json::str("q\"\\\n\u{1}")), + ( + "b", + Json::Arr(vec![Json::Num(1.0), Json::Num(0.5), Json::Null]), + ), + ("c", Json::Num(f64::NAN)), + ]); + let r = j.render(); + assert!(r.contains(r#""a": "q\"\\\n\u0001""#), "{r}"); + assert!(r.contains("0.5")); + assert!(r.contains(r#""c": null"#)); + } +} diff --git a/crates/hybrid/src/lib.rs b/crates/hybrid/src/lib.rs new file mode 100644 index 0000000..fba23fb --- /dev/null +++ b/crates/hybrid/src/lib.rs @@ -0,0 +1,30 @@ +//! BetterXen hybrid tooling: read-only inspection and measurement helpers around an +//! externally installed CrossOver. Nothing here launches a game or claims compatibility. + +pub mod cmdutil; +pub mod crossover; +pub mod frames; +pub mod host; +pub mod json; +pub mod toolchain; + +/// Value of a top-level string key in flat JSON produced by `plutil -convert json`. +pub fn host_string(json: &str, key: &str) -> Option { + let needle = format!("\"{key}\""); + let at = json.find(&needle)? + needle.len(); + let rest = json[at..] + .trim_start() + .strip_prefix(':')? + .trim_start() + .strip_prefix('"')?; + let mut out = String::new(); + let mut chars = rest.chars(); + while let Some(c) = chars.next() { + match c { + '"' => return Some(out), + '\\' => out.push(chars.next()?), + c => out.push(c), + } + } + None +} diff --git a/crates/hybrid/src/main.rs b/crates/hybrid/src/main.rs new file mode 100644 index 0000000..ef785ee --- /dev/null +++ b/crates/hybrid/src/main.rs @@ -0,0 +1,99 @@ +use betterxen_hybrid::{crossover, frames, host, json::Json, toolchain}; +use std::path::PathBuf; +use std::process::ExitCode; + +const USAGE: &str = "usage: betterxen-hybrid + host host receipt (JSON) + crossover [--app P] CrossOver installs and documented preferences (JSON) + toolchain Windows cross-compilers found on PATH (JSON) + frames frame-time statistics; file has one interval in ms per line (JSON) + receipt host + crossover + toolchain in one JSON document"; + +fn crossover_json(app: Option) -> Json { + let home = PathBuf::from(std::env::var("HOME").unwrap_or_default()); + let cands = match app { + Some(p) => vec![p], + None => crossover::candidate_paths(&home), + }; + let installs = crossover::discover(&cands); + Json::obj(vec![ + ("installed", Json::Bool(!installs.is_empty())), + ( + "installs", + Json::Arr(installs.iter().map(|i| i.to_json()).collect()), + ), + ( + "bottle_dir_preference", + Json::opt_str(crossover::preference("BottleDir")), + ), + ( + "managed_bottle_dirs_preference", + Json::opt_str(crossover::preference("ManagedBottleDirs")), + ), + ( + "searched", + Json::Arr( + cands + .iter() + .map(|p| Json::str(p.display().to_string())) + .collect(), + ), + ), + ( + "note", + Json::str( + "Only Info.plist metadata, lipo -archs and documented defaults keys are read. Bottle graphics backend and bundle internals are not interpreted (undocumented, #350).", + ), + ), + ]) +} + +fn toolchain_json() -> Json { + let path = std::env::var("PATH").unwrap_or_default(); + Json::Arr( + toolchain::probe(&path) + .iter() + .map(|c| c.to_json()) + .collect(), + ) +} + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let result: Result = match args.first().map(String::as_str) { + Some("host") => Ok(host::collect().to_json()), + Some("crossover") => { + let app = match args.get(1).map(String::as_str) { + Some("--app") => args.get(2).map(PathBuf::from), + _ => None, + }; + Ok(crossover_json(app)) + } + Some("toolchain") => Ok(toolchain_json()), + Some("frames") => match args.get(1) { + None => Err("frames needs a file".into()), + Some(f) => std::fs::read_to_string(f) + .map_err(|e| format!("{f}: {e}")) + .and_then(|t| frames::parse_intervals(&t).map_err(|e| e.to_string())) + .and_then(|v| frames::analyze(&v).map_err(|e| e.to_string())) + .map(|s| s.to_json()), + }, + Some("receipt") => Ok(Json::obj(vec![ + ("schema", Json::str("betterxen-hybrid-receipt/0")), + ("host", host::collect().to_json()), + ("crossover", crossover_json(None)), + ("windows_cross_compilers", toolchain_json()), + ])), + _ => Err(USAGE.into()), + }; + match result { + Ok(j) => { + print!("{}", j.render()); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("{e}"); + ExitCode::from(2) + } + } +} diff --git a/crates/hybrid/src/toolchain.rs b/crates/hybrid/src/toolchain.rs new file mode 100644 index 0000000..2e3e10f --- /dev/null +++ b/crates/hybrid/src/toolchain.rs @@ -0,0 +1,82 @@ +//! Probe Windows cross-compilers for original test programs (issue #364). +//! +//! Reports what is installed and what each compiler targets; it does not install anything. + +use crate::cmdutil::run; +use crate::json::Json; + +/// (name, kind). Order is the discovery order only, not a preference. +pub const CANDIDATES: &[&str] = &[ + "aarch64-w64-mingw32-clang", + "x86_64-w64-mingw32-clang", + "x86_64-w64-mingw32-gcc", + "i686-w64-mingw32-gcc", +]; + +#[derive(Debug, Clone, PartialEq)] +pub struct Compiler { + pub name: String, + pub path: String, + pub version_line: Option, + pub target_machine: Option, +} + +pub fn probe(search_path: &str) -> Vec { + CANDIDATES + .iter() + .filter_map(|name| { + let path = search_path + .split(':') + .map(|d| std::path::Path::new(d).join(name)) + .find(|p| p.is_file())?; + let p = path.to_str()?.to_string(); + Some(Compiler { + name: name.to_string(), + version_line: run(&p, &["--version"]) + .and_then(|s| s.lines().next().map(String::from)), + target_machine: run(&p, &["-dumpmachine"]), + path: p, + }) + }) + .collect() +} + +impl Compiler { + pub fn to_json(&self) -> Json { + Json::obj(vec![ + ("name", Json::str(self.name.clone())), + ("path", Json::str(self.path.clone())), + ("version", Json::opt_str(self.version_line.clone())), + ("target_machine", Json::opt_str(self.target_machine.clone())), + ]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_path_finds_nothing() { + assert!(probe("").is_empty()); + assert!(probe("/nonexistent-dir").is_empty()); + } + + #[test] + fn finds_a_stub_compiler_and_reports_its_output() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("bxhybrid-tc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("x86_64-w64-mingw32-gcc"); + std::fs::write(&f, "#!/bin/sh\nif [ \"$1\" = -dumpmachine ]; then echo x86_64-w64-mingw32; else echo stub 1.0; fi\n").unwrap(); + std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap(); + let found = probe(dir.to_str().unwrap()); + assert_eq!(found.len(), 1); + assert_eq!( + found[0].target_machine.as_deref(), + Some("x86_64-w64-mingw32") + ); + assert_eq!(found[0].version_line.as_deref(), Some("stub 1.0")); + std::fs::remove_dir_all(&dir).unwrap(); + } +}