mirror of
https://github.com/dazacode/vilauncher.git
synced 2026-12-01 21:05:33 -10:00
Run natively on macOS (Apple silicon and Intel)
From Dolo22's macOS port (github.com/Dolo22/vilauncher-for-MAC-OS, branch macos-port), only the parts it takes to run: a platform module for what differs between systems (the tools' PATH when started from Finder, opening links and folders, stopping programs, free space, game search on mounted volumes, Xcode Command Line Tools, the quarantine flag), the native app menu so Cmd+C/V/Q work, Application Support for data and settings, installing missing tools on a Mac, the .app self-update, and tauri.macos.conf.json with its entitlements. The frontend only gets the new snapshot fields and the platform check; on macOS the window keeps its traffic lights, so the drawn window controls are hidden there. Left out: the port's README, docs and wording changes and its UI. Co-authored-by: esperance <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
9de11705f1
commit
65bc2c4aab
23 files changed
+2389
-379
No files matched your search
@@ -5,6 +5,10 @@
|
||||
/dist
|
||||
*.log
|
||||
*.pfx
|
||||
# Build output beside the tree (macOS bundles, digests, staged updates)
|
||||
*.dmg
|
||||
*.app.tar.gz
|
||||
*.sha256
|
||||
.DS_Store
|
||||
.ci/
|
||||
tsconfig.tsbuildinfo
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- The launcher starts programs it did not build (a user's own game build,
|
||||
the Git and Cargo tools). Those are unsigned or signed by others, so the
|
||||
hardened runtime must not demand a matching Team ID for them. -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<!-- Some game builds and JIT-based tooling map writable, unsigned pages. -->
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<!-- Cloning projects and checking for updates over the network. -->
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
+64
-11
@@ -11,8 +11,14 @@ pub const SITE_LABEL: &str = "viportlive.com";
|
||||
/// The launcher's own code and releases on GitHub (`owner/name`).
|
||||
pub const REPOSITORY: &str = "dazacode/vilauncher";
|
||||
pub const SOURCE_URL: &str = "https://github.com/dazacode/vilauncher";
|
||||
/// The release download the updater looks for.
|
||||
/// The release download the updater looks for, for this system. The macOS
|
||||
/// bundle is a `.app.tar.gz` of a universal binary; Windows ships a portable exe.
|
||||
#[cfg(windows)]
|
||||
pub const RELEASE_ASSET: &str = "VILauncher.exe";
|
||||
#[cfg(target_os = "macos")]
|
||||
pub const RELEASE_ASSET: &str = "VILauncher-macos.app.tar.gz";
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub const RELEASE_ASSET: &str = "VILauncher.AppImage";
|
||||
|
||||
/// Where the list of projects comes from, tried in order: VIPortLive's
|
||||
/// launcher feed (PortWatch's tracker with VIPortLive's corrections and
|
||||
@@ -22,27 +28,46 @@ pub const PROJECT_SOURCES: &[(&str, &str)] = &[
|
||||
("PortWatch", "https://portwatch-vi.xyz/data/tracker.json"),
|
||||
];
|
||||
|
||||
/// The folder under %LOCALAPPDATA% (projects, pictures) and %APPDATA% (settings).
|
||||
/// The folder under the system's data folder: projects, pictures and
|
||||
/// settings. Windows: `%LOCALAPPDATA%` / `%APPDATA%`. macOS: both are
|
||||
/// `~/Library/Application Support`, the app's own folder there.
|
||||
pub const FOLDER: &str = "VILauncher";
|
||||
/// The launcher's earlier names: settings are carried over from these and
|
||||
/// already installed projects are found there (see `migrate_old_folders`).
|
||||
pub const LEGACY_FOLDERS: &[&str] = &["Mandyhub", "VI Launcher"];
|
||||
|
||||
/// %LOCALAPPDATA% (projects, pictures): on other systems, while developing,
|
||||
/// the platform's own data folder.
|
||||
/// The data folder (projects, pictures): `%LOCALAPPDATA%` on Windows, the
|
||||
/// platform's own data folder elsewhere.
|
||||
pub fn local_base() -> std::path::PathBuf {
|
||||
std::env::var_os("LOCALAPPDATA")
|
||||
.map(Into::into)
|
||||
.unwrap_or_else(data_base)
|
||||
#[cfg(windows)]
|
||||
{
|
||||
std::env::var_os("LOCALAPPDATA")
|
||||
.map(Into::into)
|
||||
.unwrap_or_else(data_base)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
data_base()
|
||||
}
|
||||
}
|
||||
|
||||
/// %APPDATA% (settings): on other systems, the platform's own data folder.
|
||||
/// The settings folder: `%APPDATA%` on Windows, the platform's own data
|
||||
/// folder elsewhere.
|
||||
pub fn roaming_base() -> std::path::PathBuf {
|
||||
std::env::var_os("APPDATA")
|
||||
.map(Into::into)
|
||||
.unwrap_or_else(data_base)
|
||||
#[cfg(windows)]
|
||||
{
|
||||
std::env::var_os("APPDATA")
|
||||
.map(Into::into)
|
||||
.unwrap_or_else(data_base)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
data_base()
|
||||
}
|
||||
}
|
||||
|
||||
/// `~/Library/Application Support` on macOS, `$XDG_DATA_HOME` (else
|
||||
/// `~/.local/share`) elsewhere.
|
||||
fn data_base() -> std::path::PathBuf {
|
||||
let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
|
||||
if cfg!(target_os = "macos") {
|
||||
@@ -58,3 +83,31 @@ fn data_base() -> std::path::PathBuf {
|
||||
|
||||
/// What the launcher calls itself to web servers.
|
||||
pub const USER_AGENT: &str = concat!("VILauncher/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_settings_and_projects_folders_are_under_one_data_folder() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
// On macOS the roaming and local folders are the same Application
|
||||
// Support folder, so settings and projects never split apart.
|
||||
assert_eq!(local_base(), roaming_base());
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(local_base().ends_with("Library/Application Support"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_release_asset_matches_the_system() {
|
||||
if cfg!(windows) {
|
||||
assert_eq!(RELEASE_ASSET, "VILauncher.exe");
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
assert!(RELEASE_ASSET.ends_with(".app.tar.gz"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
-10
@@ -50,18 +50,40 @@ fn extract_contents(zip: &mut zip::ZipArchive<File>, destination: &Path) -> io::
|
||||
}
|
||||
let mut remaining = MAX_EXPANDED_BYTES;
|
||||
let mut executables = Vec::new();
|
||||
let mut bundles = Vec::new();
|
||||
for index in 0..zip.len() {
|
||||
let mut entry = zip.by_index(index)?;
|
||||
let name = entry.name()?;
|
||||
let name = name.trim_end_matches('/');
|
||||
if entry.is_symlink() || !name.split('/').all(valid_component) {
|
||||
if !name.split('/').all(valid_component) {
|
||||
return Err(io::Error::other(
|
||||
"The build ZIP contains an unsafe file path or symbolic link.",
|
||||
"The build ZIP contains an unsafe file path.",
|
||||
));
|
||||
}
|
||||
let relative = PathBuf::from(name);
|
||||
let output = destination.join(&relative);
|
||||
if entry.is_symlink() {
|
||||
// macOS bundles carry symlinks; they are recreated where the system has them.
|
||||
let mut target = String::new();
|
||||
io::Read::read_to_string(&mut entry, &mut target)?;
|
||||
let target = target.trim();
|
||||
if target.is_empty()
|
||||
|| target.starts_with('/')
|
||||
|| !target.split('/').all(valid_component)
|
||||
{
|
||||
return Err(io::Error::other(
|
||||
"The build ZIP contains an unsafe symbolic link.",
|
||||
));
|
||||
}
|
||||
fs::create_dir_all(output.parent().expect("a link has a parent"))?;
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(target, &output)?;
|
||||
continue;
|
||||
}
|
||||
if entry.is_dir() {
|
||||
if name.ends_with(".app") {
|
||||
bundles.push(relative.clone());
|
||||
}
|
||||
fs::create_dir_all(output)?;
|
||||
continue;
|
||||
}
|
||||
@@ -72,32 +94,48 @@ fn extract_contents(zip: &mut zip::ZipArchive<File>, destination: &Path) -> io::
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(output)?;
|
||||
.open(&output)?;
|
||||
let written = io::copy(&mut io::Read::take(&mut entry, remaining + 1), &mut file)?;
|
||||
remaining = remaining
|
||||
.checked_sub(written)
|
||||
.ok_or_else(|| io::Error::other("The extracted build exceeds 8 GiB."))?;
|
||||
if relative
|
||||
// A program: a Windows exe, a Mach-O binary or a script. Data files
|
||||
// (dlls, rpf) are not even read for their first bytes.
|
||||
let executable = relative
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("exe"))
|
||||
{
|
||||
|| crate::platform::binary_kind(&output) != crate::platform::Binary::Unknown;
|
||||
if executable {
|
||||
crate::platform::make_executable(&output);
|
||||
executables.push(relative);
|
||||
}
|
||||
}
|
||||
// Apple's quarantine would block a freshly unpacked game on first start.
|
||||
crate::platform::clear_quarantine(destination);
|
||||
let mut victory = executables.iter().filter(|path| is_victory(path));
|
||||
match (victory.next(), victory.next(), executables.as_slice()) {
|
||||
let chosen = match (victory.next(), victory.next(), executables.as_slice()) {
|
||||
(Some(exe), None, _) | (None, None, [exe]) => Ok(exe.clone()),
|
||||
(None, None, []) => Err(io::Error::other("The ZIP contains no Windows executable.")),
|
||||
(None, None, []) => match bundles.as_slice() {
|
||||
[app] => Ok(app.clone()),
|
||||
[] => Err(io::Error::other("The ZIP contains no program.")),
|
||||
_ => Err(io::Error::other(
|
||||
"The ZIP contains multiple possible launch programs.",
|
||||
)),
|
||||
},
|
||||
_ => Err(io::Error::other(
|
||||
"The ZIP contains multiple possible launch executables.",
|
||||
)),
|
||||
}
|
||||
}?;
|
||||
// Bundles keep their own inner permissions; a lone binary is made runnable.
|
||||
crate::platform::make_executable(&destination.join(&chosen));
|
||||
Ok(chosen)
|
||||
}
|
||||
|
||||
/// Whether a path is the victory program, named either way.
|
||||
pub fn is_victory(executable: &Path) -> bool {
|
||||
executable
|
||||
.file_name()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("victory.exe"))
|
||||
.file_stem()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("victory"))
|
||||
}
|
||||
|
||||
/// Read only literal defaults from a companion script. The script itself is never run.
|
||||
|
||||
+90
-12
@@ -21,6 +21,8 @@ pub(crate) const FIX_GRAPHICS_MEMORY: &str = "graphics-memory";
|
||||
pub(crate) const FIX_GRAPHICS_DEVICE: &str = "graphics-device";
|
||||
pub(crate) const FIX_DRIVER_PAGE: &str = "driver-page";
|
||||
pub(crate) const FIX_REPO_SWITCH: &str = "repo-switch";
|
||||
pub(crate) const FIX_QUARANTINE: &str = "quarantine";
|
||||
pub(crate) const FIX_EXEC_BIT: &str = "exec-bit";
|
||||
|
||||
/// Microsoft's D3D12 Agility SDK files and the package that holds them. Each copy is
|
||||
/// checked against a SHA-256: these when the project's own build names no version.
|
||||
@@ -627,7 +629,7 @@ pub(crate) fn preflight(check: &Check) -> Vec<Finding> {
|
||||
heavy: true,
|
||||
data: None,
|
||||
});
|
||||
} else if !agility_ok(check.exe.parent().unwrap_or(Path::new(".")), &agility) {
|
||||
} else if cfg!(windows) && !agility_ok(check.exe.parent().unwrap_or(Path::new(".")), &agility) {
|
||||
found.push(Finding {
|
||||
title: "The D3D12 Agility SDK files are missing or not the expected version.".to_string(),
|
||||
detail: "The game needs them in D3D12\\ next to its exe, or device creation fails with 0x887E0003. Fix and verify finds the project's version, installs it and checks every hash.".to_string(),
|
||||
@@ -636,6 +638,38 @@ pub(crate) fn preflight(check: &Check) -> Vec<Finding> {
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
// macOS: a program Gatekeeper or a lost permission bit refuses to start.
|
||||
if check.installed && check.exe.is_file() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let executable = check
|
||||
.exe
|
||||
.metadata()
|
||||
.map(|meta| meta.permissions().mode() & 0o111 != 0)
|
||||
.unwrap_or(true);
|
||||
if !executable {
|
||||
found.push(Finding {
|
||||
title: "The build's program is not marked executable.".to_string(),
|
||||
detail: "macOS refuses to start it as it is. Fix and verify sets the execute bit and checks that the system sees it."
|
||||
.to_string(),
|
||||
fix: Some(FIX_EXEC_BIT),
|
||||
heavy: false,
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
if crate::platform::is_quarantined(check.exe) {
|
||||
found.push(Finding {
|
||||
title: "macOS holds the build in quarantine.".to_string(),
|
||||
detail: "Gatekeeper downloaded-build protection stops an unsigned program. Fix and verify clears the quarantine flag and checks it is gone."
|
||||
.to_string(),
|
||||
fix: Some(FIX_QUARANTINE),
|
||||
heavy: false,
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !check.game_ok {
|
||||
if check.game_dir.as_os_str().is_empty() {
|
||||
found.push(Finding {
|
||||
@@ -674,7 +708,10 @@ pub(crate) fn preflight(check: &Check) -> Vec<Finding> {
|
||||
if !crate::tools::detect().ready() {
|
||||
found.push(Finding {
|
||||
title: "Building is missing one or more tools.".to_string(),
|
||||
detail: "Fix and verify installs the missing Git, Rust or C++ build tools with winget and looks again.".to_string(),
|
||||
detail: format!(
|
||||
"Fix and verify installs the missing Git, Rust or {} and looks again.",
|
||||
crate::tools::BUILD_TOOLS.to_lowercase()
|
||||
),
|
||||
fix: Some(FIX_TOOLS),
|
||||
heavy: true,
|
||||
data: None,
|
||||
@@ -757,7 +794,7 @@ pub(crate) fn from_log(lines: &[String]) -> Vec<Finding> {
|
||||
.any(|line| needles.iter().any(|needle| line.contains(needle)))
|
||||
};
|
||||
let mut found = Vec::new();
|
||||
if has(&["Agility SDK runtime missing", "0x887E0003", "0x887A002D"]) {
|
||||
if cfg!(windows) && has(&["Agility SDK runtime missing", "0x887E0003", "0x887A002D"]) {
|
||||
found.push(Finding {
|
||||
title: "The game could not load the D3D12 Agility SDK.".to_string(),
|
||||
detail: "Fix and verify installs and checks the files the project needs, then Play again after it passes.".to_string(),
|
||||
@@ -814,7 +851,29 @@ pub(crate) fn from_log(lines: &[String]) -> Vec<Finding> {
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
if has(&["Access is denied", "permission denied", "os error 5"]) {
|
||||
if cfg!(target_os = "macos")
|
||||
&& has(&[
|
||||
"cannot be opened because the developer cannot be verified",
|
||||
"is damaged and can't be opened",
|
||||
"Bad CPU type in executable",
|
||||
])
|
||||
{
|
||||
found.push(Finding {
|
||||
title: "macOS refused to start the build.".to_string(),
|
||||
detail: "Gatekeeper blocked an unsigned program, or the build is for another processor. Fix and verify clears the quarantine flag; Bad CPU means a build made for Intel only (or Apple silicon only)."
|
||||
.to_string(),
|
||||
fix: Some(FIX_QUARANTINE),
|
||||
heavy: false,
|
||||
data: None,
|
||||
});
|
||||
}
|
||||
if has(&[
|
||||
"Access is denied",
|
||||
"permission denied",
|
||||
"os error 5",
|
||||
"os error 13",
|
||||
"Permission denied (os error 13)",
|
||||
]) {
|
||||
found.push(Finding {
|
||||
title: "A file or folder could not be written.".to_string(),
|
||||
detail: "Fix and verify clears read-only flags and proves the saves and cache folders writable.".to_string(),
|
||||
@@ -892,14 +951,26 @@ mod tests {
|
||||
free_bytes: None,
|
||||
gpu: None,
|
||||
};
|
||||
assert_eq!(preflight(&check).len(), 1);
|
||||
assert_eq!(preflight(&check)[0].fix, Some(FIX_AGILITY));
|
||||
let findings = preflight(&check);
|
||||
assert_eq!(findings.len(), 1);
|
||||
// On macOS the same build first trips the missing execute bit; the
|
||||
// Agility check is a Windows one.
|
||||
assert_eq!(
|
||||
findings[0].fix,
|
||||
Some(if cfg!(windows) {
|
||||
FIX_AGILITY
|
||||
} else {
|
||||
FIX_EXEC_BIT
|
||||
})
|
||||
);
|
||||
// The build's files are not the real Microsoft ones, so the fix falls back
|
||||
// to Microsoft's package (this needs the network).
|
||||
if let Err(error) = fix(FIX_AGILITY, &exe, &repo, &root.join("cache")) {
|
||||
eprintln!("network fix skipped: {error}");
|
||||
if cfg!(windows) {
|
||||
if let Err(error) = fix(FIX_AGILITY, &exe, &repo, &root.join("cache")) {
|
||||
eprintln!("network fix skipped: {error}");
|
||||
}
|
||||
assert!(agility_ok(exe.parent().unwrap(), &agility_for(&repo)));
|
||||
}
|
||||
assert!(agility_ok(exe.parent().unwrap(), &agility_for(&repo)));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
@@ -935,7 +1006,6 @@ mod tests {
|
||||
];
|
||||
let found = from_log(&log);
|
||||
for fix_id in [
|
||||
FIX_AGILITY,
|
||||
FIX_GRAPHICS_DEVICE,
|
||||
FIX_DRIVER_PAGE,
|
||||
FIX_GRAPHICS_MEMORY,
|
||||
@@ -947,6 +1017,11 @@ mod tests {
|
||||
"missing {fix_id}"
|
||||
);
|
||||
}
|
||||
// The log is a Windows one; the Agility check stays Windows-only.
|
||||
assert_eq!(
|
||||
found.iter().any(|f| f.fix == Some(FIX_AGILITY)),
|
||||
cfg!(windows)
|
||||
);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
@@ -1161,8 +1236,11 @@ mod tests {
|
||||
fn a_crash_log_names_the_known_problem() {
|
||||
let lines = vec!["Error: Agility SDK runtime missing: D3D12Core.dll not found".to_string()];
|
||||
let found = from_log(&lines);
|
||||
assert_eq!(found.len(), 1);
|
||||
assert_eq!(found[0].fix, Some(FIX_AGILITY));
|
||||
// A Windows-only problem: it is not raised on macOS.
|
||||
assert_eq!(found.len(), usize::from(cfg!(windows)));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(found[0].fix, Some(FIX_AGILITY));
|
||||
}
|
||||
assert!(from_log(&["ok".to_string()]).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -27,11 +27,7 @@ pub(crate) fn write(workspace: &Path, slug: &str, stage: &str, lines: &[String])
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let private = [
|
||||
std::env::var("USERNAME").unwrap_or_default(),
|
||||
std::env::var("USERPROFILE").unwrap_or_default(),
|
||||
workspace.display().to_string(),
|
||||
];
|
||||
let private = crate::report::private_paths(workspace);
|
||||
|
||||
let mut text = format!("== {} | {}\n", utc_now(), stage.trim());
|
||||
let start = lines.len().saturating_sub(MAX_LINES);
|
||||
|
||||
+182
-99
@@ -559,16 +559,31 @@ fn built_exe(repo: &str) -> PathBuf {
|
||||
let dir = repo_dir(repo);
|
||||
let workspace = cargo_workspace(&dir).unwrap_or_else(|_| dir.clone());
|
||||
let target = target_dir(repo);
|
||||
let executable = target
|
||||
.join(detect_build_profile(&workspace))
|
||||
.join("victory.exe");
|
||||
let previous = target.join("release").join("victory.exe");
|
||||
let executable = victory_program(&target.join(detect_build_profile(&workspace)));
|
||||
let previous = victory_program(&target.join("release"));
|
||||
if workspace != dir && !executable.is_file() && previous.is_file() {
|
||||
return previous;
|
||||
}
|
||||
executable
|
||||
}
|
||||
|
||||
/// The program a victory build leaves in `dir`: the native name (`victory`),
|
||||
/// else the `.exe` a Windows build made, else the native name for the error.
|
||||
fn victory_program(dir: &Path) -> PathBuf {
|
||||
let native = dir.join(crate::platform::exe_name("victory"));
|
||||
if native.is_file() {
|
||||
return native;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let windows = dir.join("victory.exe");
|
||||
if windows.is_file() {
|
||||
return windows;
|
||||
}
|
||||
}
|
||||
native
|
||||
}
|
||||
|
||||
/// Most projects build at the root. Some wrap a Cargo workspace one level down.
|
||||
fn cargo_workspace(repo: &Path) -> Result<PathBuf, String> {
|
||||
if repo.join("Cargo.toml").is_file() {
|
||||
@@ -699,7 +714,7 @@ fn remote_head(p: &Project) -> Option<String> {
|
||||
fn repo_state(p: &Project) -> RepoState {
|
||||
if let Some(exe) = p.archive_program() {
|
||||
return RepoState {
|
||||
installed: exe.is_file(),
|
||||
installed: crate::platform::is_program(&exe),
|
||||
activity: build_activity::BuildActivity::read(&target_dir(&p.repo)),
|
||||
..RepoState::default()
|
||||
};
|
||||
@@ -753,6 +768,12 @@ fn find_game_in(dir: &Path, depth: u32) -> Option<PathBuf> {
|
||||
"program files (x86)",
|
||||
"programdata",
|
||||
"appdata",
|
||||
// macOS
|
||||
"library",
|
||||
"system",
|
||||
"private",
|
||||
"applications",
|
||||
"volumes",
|
||||
];
|
||||
if name.starts_with('$') || name.starts_with('.') || skip.contains(&name.as_str()) {
|
||||
continue;
|
||||
@@ -775,32 +796,23 @@ fn folder_tail(saved: &Path) -> Option<PathBuf> {
|
||||
(!tail.as_os_str().is_empty()).then_some(tail)
|
||||
}
|
||||
|
||||
/// The same folder on another connected drive that holds the game, for when the
|
||||
/// drive letter changed (an external SSD that came back as F: instead of E:).
|
||||
/// The same folder on another connected drive or volume that holds the game,
|
||||
/// for when the drive letter or volume name changed (an external SSD that
|
||||
/// came back as F: instead of E:, a volume that remounted under another name).
|
||||
fn find_moved_game(saved: &Path) -> Option<PathBuf> {
|
||||
let tail = folder_tail(saved)?;
|
||||
('A'..='Z')
|
||||
.map(|letter| PathBuf::from(format!("{letter}:\\")))
|
||||
.filter(|root| root.is_dir())
|
||||
.map(|root| root.join(&tail))
|
||||
crate::platform::moved_folder_candidates(saved, &tail)
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.join(EXE_NAME).is_file())
|
||||
}
|
||||
|
||||
/// Whether the drive a folder is on is connected. A folder without a drive letter counts as connected.
|
||||
fn drive_connected(dir: &Path) -> bool {
|
||||
match dir.components().next() {
|
||||
Some(Component::Prefix(_)) => dir.components().take(2).collect::<PathBuf>().exists(),
|
||||
_ => true,
|
||||
}
|
||||
crate::platform::drive_connected(dir)
|
||||
}
|
||||
|
||||
/// Every drive's folders, three levels down, for the game's exe.
|
||||
/// Every drive's or volume's folders, three levels down, for the game's exe.
|
||||
fn search_drives() -> Result<String, String> {
|
||||
for letter in b'C'..=b'Z' {
|
||||
let root = PathBuf::from(format!("{}:\\", letter as char));
|
||||
if !root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
for root in crate::platform::game_search_roots() {
|
||||
if let Some(found) = find_game_in(&root, 3) {
|
||||
return Ok(found.display().to_string());
|
||||
}
|
||||
@@ -1142,14 +1154,10 @@ fn fetch_list(name: &str, url: &str) -> Result<Vec<Project>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
/// Runs a spawned program without a console window opening (Windows).
|
||||
pub(crate) fn hide_window(c: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
c.creation_flags(CREATE_NO_WINDOW);
|
||||
crate::platform::configure_background_command(c);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
pub(crate) fn hide_window(_: &mut Command) {}
|
||||
|
||||
impl App {
|
||||
fn import_build_zip(&mut self, ctx: &Ctx, input: PathBuf) {
|
||||
@@ -1728,7 +1736,7 @@ fn build_project(
|
||||
if victory {
|
||||
cargo.args(["-p", "victory"]);
|
||||
run(job, ctx, &mut cargo)?;
|
||||
let executable = target.join(profile).join("victory.exe");
|
||||
let executable = victory_program(&target.join(profile));
|
||||
if !executable.is_file() {
|
||||
return Err(format!("the build made no {}", executable.display()));
|
||||
}
|
||||
@@ -1990,30 +1998,53 @@ fn clear_read_only(dir: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends every process whose program lives under `dir` (the game and the victory.exe that runs it).
|
||||
/// Ends every process whose program lives under `dir` (the game and the runner).
|
||||
fn stop_programs_under(dir: &Path) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let folder = dir.display().to_string().replace('\'', "''");
|
||||
let script = format!(
|
||||
"Get-Process | Where-Object {{ $_.Path -and $_.Path.StartsWith('{folder}', [StringComparison]::OrdinalIgnoreCase) }} | Stop-Process -Force -ErrorAction SilentlyContinue"
|
||||
);
|
||||
let mut c = Command::new("powershell");
|
||||
c.args(["-NoProfile", "-NonInteractive", "-Command", &script]);
|
||||
hide_window(&mut c);
|
||||
let _ = c.status();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = dir;
|
||||
crate::platform::stop_programs_under(dir);
|
||||
}
|
||||
|
||||
/// The victory.exe `p` runs with: its build, or a build already on this PC.
|
||||
/// Checks a program can run here: a native or script file, with its execute
|
||||
/// bit, not under quarantine. Fixes what it can and says what the player can
|
||||
/// do when it cannot. A macOS `.app` bundle is handed back as it is.
|
||||
fn runnable(path: PathBuf) -> Result<PathBuf, String> {
|
||||
let bundle = path.extension().is_some_and(|ext| ext == "app") && path.is_dir();
|
||||
if !bundle && !path.is_file() {
|
||||
return Err(format!(
|
||||
"{} is missing: install the build again.",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
if !bundle {
|
||||
if crate::platform::binary_kind(&path) == crate::platform::Binary::Windows
|
||||
&& cfg!(target_os = "macos")
|
||||
{
|
||||
return Err(format!(
|
||||
"{} is a Windows program and this Mac cannot run it directly. Build the project from source on macOS, or run it with a compatibility runner such as CrossOver or Whisky.",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
crate::platform::make_executable(&path);
|
||||
if crate::platform::is_quarantined(&path) {
|
||||
crate::platform::clear_quarantine(&path);
|
||||
if crate::platform::is_quarantined(&path) {
|
||||
return Err(format!(
|
||||
"macOS still holds {} in quarantine. Allow it in System Settings > Privacy & Security, or run: xattr -dr com.apple.quarantine \"{}\"",
|
||||
path.display(),
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// The victory program `p` runs with: its build, or a build already on this PC.
|
||||
fn project_exe(p: &Project) -> Result<PathBuf, String> {
|
||||
let exe = p
|
||||
.archive_program()
|
||||
.or_else(|| p.local_exe.as_ref().map(PathBuf::from))
|
||||
.unwrap_or_else(|| built_exe(&p.repo));
|
||||
if exe.is_file() {
|
||||
if crate::platform::is_program(&exe) {
|
||||
Ok(exe)
|
||||
} else {
|
||||
Err("this project is not installed yet: press Install".into())
|
||||
@@ -2133,7 +2164,7 @@ fn a_moved_game_folder_keeps_its_path_under_the_drive() {
|
||||
|
||||
/// Fills the same shader cache as Play, using the commands the installed fork exposes.
|
||||
fn warm(job: &Arc<Mutex<Job>>, ctx: &Ctx, p: &Project, l: &Launch) -> Result<(), String> {
|
||||
let exe = project_exe(p)?;
|
||||
let (exe, _) = crate::platform::program_for(&runnable(project_exe(p)?)?);
|
||||
let files: Vec<PathBuf> = WARM_FILES
|
||||
.iter()
|
||||
.map(|f| l.game_dir.join(f))
|
||||
@@ -2247,33 +2278,66 @@ fn fix_game_files(l: &mut Launch, log: &dyn Fn(String)) -> Result<String, String
|
||||
Err("No folder with every required game file was found. Choose it with Browse.".into())
|
||||
}
|
||||
|
||||
/// Installs the missing build tools and looks again.
|
||||
/// Installs the missing build tools with the system's own installer and looks again.
|
||||
fn install_missing_tools(job: &Arc<Mutex<Job>>, ctx: &Ctx) -> Result<(), String> {
|
||||
let have = tools::detect();
|
||||
if have.ready() {
|
||||
return Ok(());
|
||||
}
|
||||
if !tools::has_winget() {
|
||||
return Err("winget (the Windows package manager) is not on this PC. Install them by hand: git-scm.com, rustup.rs and the Visual Studio Build Tools (Desktop development with C++).".into());
|
||||
if !tools::has_manager() {
|
||||
return Err(install_by_hand());
|
||||
}
|
||||
for (what, args) in tools::install_steps(&have) {
|
||||
for step in tools::install_steps(&have) {
|
||||
stage(
|
||||
job,
|
||||
ctx,
|
||||
&format!("Installing {what} (this can take a while)"),
|
||||
&format!("Installing {} (this can take a while)", step.what),
|
||||
);
|
||||
let mut c = Command::new("winget");
|
||||
c.args(&args);
|
||||
run(job, ctx, &mut c).map_err(|error| format!("{what}: {error}"))?;
|
||||
let mut c = Command::new(step.program);
|
||||
c.args(&step.args);
|
||||
// Apple's installer returns at once and asks the player in its own window;
|
||||
// wait for the tools to answer rather than for the command.
|
||||
let asked = step.program.ends_with("xcode-select");
|
||||
run(job, ctx, &mut c).map_err(|error| format!("{}: {error}", step.what))?;
|
||||
if asked {
|
||||
stage(job, ctx, "Waiting for the Command Line Tools installer");
|
||||
if !tools::wait_until_installed(step.what, 900) {
|
||||
return Err(format!(
|
||||
"the {} installer was not finished (its window may still be open). Run Install missing tools again when it is.",
|
||||
step.what
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What to install by hand, on this system.
|
||||
fn install_by_hand() -> String {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
"winget (the Windows package manager) is not on this PC. Install them by hand: git-scm.com, rustup.rs and the Visual Studio Build Tools (Desktop development with C++).".into()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
"Install them by hand: `xcode-select --install` in Terminal, then GitHub Desktop or Homebrew's git, then rustup from rustup.rs.".into()
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
"Install git, Rust and a C++ toolchain with the system's package manager.".into()
|
||||
}
|
||||
}
|
||||
|
||||
fn fix_tools(job: &Arc<Mutex<Job>>, ctx: &Ctx) -> Result<String, String> {
|
||||
install_missing_tools(job, ctx)?;
|
||||
let have = tools::detect();
|
||||
if have.ready() {
|
||||
Ok("Git, Rust and the C++ build tools are installed and answer.".into())
|
||||
Ok(format!(
|
||||
"Git, Rust and the {} are installed and answer{}. The installed git is {}.",
|
||||
tools::BUILD_TOOLS,
|
||||
if cfg!(windows) { "" } else { " on this Mac" },
|
||||
tools::git_version().unwrap_or_else(|| "git".into())
|
||||
))
|
||||
} else {
|
||||
Err(format!(
|
||||
"these tools still do not answer: {}.",
|
||||
@@ -2293,7 +2357,7 @@ fn fix_build(
|
||||
}
|
||||
stage(job, ctx, "Rebuilding the missing program");
|
||||
install(job, ctx, p, project_installed(&p.repo), l)?;
|
||||
let exe = project_exe(p)?;
|
||||
let (exe, _) = crate::platform::program_for(&project_exe(p)?);
|
||||
let mut c = Command::new(&exe);
|
||||
c.arg("--version");
|
||||
hide_window(&mut c);
|
||||
@@ -2325,6 +2389,54 @@ fn fix_cache(p: &Project, job: &Arc<Mutex<Job>>) -> Result<String, String> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Clears macOS's quarantine flag from the build and checks it is gone.
|
||||
fn fix_quarantine(exe: &Path) -> Result<String, String> {
|
||||
if !crate::platform::is_quarantined(exe) {
|
||||
return Ok(format!("{} is no longer in quarantine.", exe.display()));
|
||||
}
|
||||
crate::platform::clear_quarantine(exe);
|
||||
if crate::platform::is_quarantined(exe) {
|
||||
return Err(format!(
|
||||
"{} is still in quarantine. Allow it in System Settings > Privacy & Security, or run: xattr -dr com.apple.quarantine \"{}\"",
|
||||
exe.display(),
|
||||
exe.display()
|
||||
));
|
||||
}
|
||||
Ok(format!(
|
||||
"Cleared the quarantine flag from {} and checked it.",
|
||||
exe.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Sets the execute bit on the build and checks the system sees it.
|
||||
fn fix_exec_bit(exe: &Path) -> Result<String, String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
crate::platform::make_executable(exe);
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = exe
|
||||
.metadata()
|
||||
.map_err(|error| error.to_string())?
|
||||
.permissions()
|
||||
.mode();
|
||||
if mode & 0o111 == 0 {
|
||||
return Err(format!(
|
||||
"{} still is not executable (mode {mode:o}).",
|
||||
exe.display()
|
||||
));
|
||||
}
|
||||
Ok(format!(
|
||||
"Set the execute bit on {} and checked it.",
|
||||
exe.display()
|
||||
))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = exe;
|
||||
Ok("The system has no execute bit.".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears read-only flags and proves both folders can be written.
|
||||
fn fix_permissions(p: &Project) -> Result<String, String> {
|
||||
let ws = workspace();
|
||||
@@ -2345,32 +2457,8 @@ fn fix_permissions(p: &Project) -> Result<String, String> {
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn free_bytes(dir: &Path) -> Option<u64> {
|
||||
let drive: String = dir
|
||||
.components()
|
||||
.take(2)
|
||||
.collect::<PathBuf>()
|
||||
.display()
|
||||
.to_string();
|
||||
let mut c = Command::new("fsutil");
|
||||
c.args(["volume", "diskfree", &drive]);
|
||||
hide_window(&mut c);
|
||||
let output = c.output().ok()?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let after = text.lines().next()?.split(':').nth(1)?;
|
||||
let digits: String = after
|
||||
.split('(')
|
||||
.next()?
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn free_bytes(_dir: &Path) -> Option<u64> {
|
||||
None
|
||||
crate::platform::free_bytes(dir)
|
||||
}
|
||||
|
||||
fn fix_disk(p: &Project, job: &Arc<Mutex<Job>>) -> Result<String, String> {
|
||||
@@ -2528,12 +2616,7 @@ fn open_driver_page(vendor: Option<&str>) -> Result<String, String> {
|
||||
}
|
||||
|
||||
fn open_url(url: &str) -> Result<(), String> {
|
||||
let mut c = Command::new("cmd");
|
||||
c.args(["/C", "start", "", url]);
|
||||
hide_window(&mut c);
|
||||
c.status()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open {url}: {error}"))
|
||||
crate::platform::open_url(url)
|
||||
}
|
||||
|
||||
/// Runs one finding's fix with every check logged. `Ok(None)` is a finding with no automatic fix.
|
||||
@@ -2579,6 +2662,8 @@ fn apply_finding(
|
||||
diagnose::FIX_GRAPHICS_DEVICE => fix_graphics(job, p, l, false),
|
||||
diagnose::FIX_DRIVER_PAGE => open_driver_page(l.gpu_vendor),
|
||||
diagnose::FIX_REPO_SWITCH => fix_repo_switch(job, p, l, finding.data.as_deref()),
|
||||
diagnose::FIX_QUARANTINE => fix_quarantine(exe),
|
||||
diagnose::FIX_EXEC_BIT => fix_exec_bit(exe),
|
||||
_ => Err(format!("There is no fix called {id}.")),
|
||||
}
|
||||
.map(Some)
|
||||
@@ -2691,23 +2776,21 @@ fn play(
|
||||
choice: &saves::LaunchSave,
|
||||
) -> Result<(), String> {
|
||||
if p.runs_standalone() {
|
||||
let (exe, dir) = if let Some(exe) = p.archive_program() {
|
||||
let dir = exe
|
||||
.parent()
|
||||
.ok_or("The archive executable has no parent folder.")?
|
||||
.to_owned();
|
||||
(exe, dir)
|
||||
let raw = if let Some(exe) = p.archive_program() {
|
||||
exe
|
||||
} else {
|
||||
let exe = rust_install(&p.repo)
|
||||
.and_then(|install| install.executable)
|
||||
.ok_or("This Rust workspace has no runnable binary.")?;
|
||||
(
|
||||
target_dir(&p.repo).join(exe),
|
||||
cargo_workspace(&repo_dir(&p.repo))?,
|
||||
)
|
||||
target_dir(&p.repo).join(exe)
|
||||
};
|
||||
// A `.app` runs its own program; anything else is checked first.
|
||||
let (exe, dir) = crate::platform::program_for(&runnable(raw)?);
|
||||
let mut command = Command::new(exe);
|
||||
command.current_dir(dir).args(&l.program_args);
|
||||
if let Some(dir) = dir {
|
||||
command.current_dir(dir);
|
||||
}
|
||||
command.args(&l.program_args);
|
||||
stage(job, ctx, "Checking known problems");
|
||||
run_fixes(job, ctx, p, l, false)?;
|
||||
stage(job, ctx, "Playing");
|
||||
@@ -2735,7 +2818,7 @@ fn play(
|
||||
}
|
||||
return result;
|
||||
}
|
||||
let exe = project_exe(p)?;
|
||||
let (exe, _) = crate::platform::program_for(&runnable(project_exe(p)?)?);
|
||||
// Quick known problems are repaired and checked before the game starts; one that cannot
|
||||
// be repaired stops the launch here, rather than starting a game that will fail. Heavy ones
|
||||
// (a tool install, a rebuild) are left to Fix and verify.
|
||||
|
||||
@@ -257,13 +257,13 @@ impl App {
|
||||
(job.stage.clone(), job.log.clone())
|
||||
};
|
||||
let system = self.system.lock().unwrap().clone().unwrap_or_default();
|
||||
let mut private = vec![
|
||||
let mut private = crate::report::private_paths(&workspace());
|
||||
private.extend([
|
||||
std::env::var("USERNAME").unwrap_or_default(),
|
||||
std::env::var("USERPROFILE").unwrap_or_default(),
|
||||
self.saved.install_dir.clone(),
|
||||
self.saved.game_dir.clone(),
|
||||
workspace().display().to_string(),
|
||||
];
|
||||
]);
|
||||
private.retain(|s| !s.trim().is_empty());
|
||||
let report = crate::report::make(&crate::report::Facts {
|
||||
project: &p.name,
|
||||
@@ -670,9 +670,9 @@ impl App {
|
||||
Value::Null
|
||||
}
|
||||
Action::Open { what, repo } => {
|
||||
let path = match (what.as_str(), repo) {
|
||||
let path = match (what.as_str(), repo.as_deref()) {
|
||||
("project_folder", Some(repo)) => {
|
||||
let p = self.project(&repo)?;
|
||||
let p = self.project(repo)?;
|
||||
p.local_exe
|
||||
.as_deref()
|
||||
.and_then(|exe| Path::new(exe).parent())
|
||||
@@ -691,7 +691,15 @@ impl App {
|
||||
_ => return Err(format!("Nothing to open for {what}.")),
|
||||
};
|
||||
let _ = std::fs::create_dir_all(&path);
|
||||
open_folder(&path)?;
|
||||
// A build's folder opens with its program selected where the
|
||||
// system can (Finder); everything else opens the folder itself.
|
||||
match repo.as_deref().and_then(|repo| self.project(repo).ok()) {
|
||||
Some(p) if what == "project_folder" => match p.local_exe.as_deref() {
|
||||
Some(exe) if Path::new(exe).is_file() => reveal(Path::new(exe))?,
|
||||
_ => open_folder(&path)?,
|
||||
},
|
||||
_ => open_folder(&path)?,
|
||||
}
|
||||
Value::Null
|
||||
}
|
||||
Action::ExportLog { path } => {
|
||||
@@ -841,26 +849,8 @@ impl App {
|
||||
j.pid
|
||||
};
|
||||
if let Some(pid) = pid {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// A window close first, so the game can save; forced only if it is still running a few seconds later.
|
||||
let pid = pid.to_string();
|
||||
std::thread::spawn(move || {
|
||||
let mut close = Command::new("taskkill");
|
||||
close.args(["/PID", &pid, "/T"]);
|
||||
hide_window(&mut close);
|
||||
let _ = close.status();
|
||||
std::thread::sleep(std::time::Duration::from_secs(8));
|
||||
let mut force = Command::new("taskkill");
|
||||
force.args(["/PID", &pid, "/T", "/F"]);
|
||||
hide_window(&mut force);
|
||||
let _ = force.status();
|
||||
});
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = Command::new("kill").arg(pid.to_string()).spawn();
|
||||
}
|
||||
// A close first, so the game can save; forced only if it is still running later.
|
||||
crate::platform::stop_program(pid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -916,26 +906,15 @@ fn open_link(url: &str) -> Result<(), String> {
|
||||
if !plain {
|
||||
return Err("Only https links can be opened from the launcher.".into());
|
||||
}
|
||||
std::process::Command::new("explorer.exe")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open the link: {error}"))
|
||||
crate::platform::open_url(url)
|
||||
}
|
||||
|
||||
fn open_folder(path: &Path) -> Result<(), String> {
|
||||
let program = if cfg!(windows) {
|
||||
"explorer"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
Command::new(program)
|
||||
.arg(path)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|e| format!("Could not open {}: {e}", path.display()))
|
||||
crate::platform::open_folder(path)
|
||||
}
|
||||
|
||||
fn reveal(path: &Path) -> Result<(), String> {
|
||||
crate::platform::reveal(path)
|
||||
}
|
||||
|
||||
/// The saves a project can start from: this build's, other builds' and the favourites.
|
||||
|
||||
@@ -34,6 +34,9 @@ struct BrandView {
|
||||
site: &'static str,
|
||||
site_label: &'static str,
|
||||
source: &'static str,
|
||||
/// "windows", "macos" or the system's own name: the UI follows it for
|
||||
/// labels, shortcuts and window chrome.
|
||||
platform: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -64,6 +67,9 @@ pub(crate) struct ProjectView {
|
||||
custom: bool,
|
||||
/// "git", "zip" or "local".
|
||||
kind: &'static str,
|
||||
/// The program's format: "windows", "native", "script" or "unknown". A
|
||||
/// Windows program needs a compatibility runner on a Mac.
|
||||
binary: Option<&'static str>,
|
||||
web_url: Option<String>,
|
||||
listing: super::Listing,
|
||||
installed: bool,
|
||||
@@ -146,6 +152,9 @@ struct FilesView {
|
||||
struct ToolsView {
|
||||
ready: bool,
|
||||
missing: Vec<&'static str>,
|
||||
/// What the build tools are called here ("C++ build tools" / "Xcode Command Line Tools").
|
||||
build_tools: &'static str,
|
||||
install_hint: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -177,15 +186,9 @@ pub(crate) struct LogView {
|
||||
pub(crate) omitted: usize,
|
||||
}
|
||||
|
||||
/// A time as the player's clock shows it (Windows only; elsewhere none).
|
||||
/// A time as the player's clock shows it.
|
||||
fn local_time(seconds: u64) -> Option<String> {
|
||||
#[cfg(windows)]
|
||||
return build_activity::local_time(seconds);
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = seconds;
|
||||
None
|
||||
}
|
||||
crate::platform::local_time(seconds)
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -228,6 +231,7 @@ impl App {
|
||||
site: brand::SITE,
|
||||
site_label: brand::SITE_LABEL,
|
||||
source: brand::SOURCE_URL,
|
||||
platform: std::env::consts::OS,
|
||||
},
|
||||
list: ListView {
|
||||
status,
|
||||
@@ -268,6 +272,8 @@ impl App {
|
||||
tools: tools::current().map(|t| ToolsView {
|
||||
ready: t.ready(),
|
||||
missing: t.missing(),
|
||||
build_tools: tools::BUILD_TOOLS,
|
||||
install_hint: tools::INSTALL_HINT,
|
||||
}),
|
||||
job,
|
||||
updater: self.updater_view(),
|
||||
@@ -351,6 +357,15 @@ impl App {
|
||||
probe_rays: script_preset::enabled(&effective, script_preset::PROBE_RAYS),
|
||||
hooks: script_preset::enabled(&effective, script_preset::HOOKS),
|
||||
};
|
||||
let binary = p
|
||||
.archive_program()
|
||||
.or_else(|| p.local_exe.as_deref().map(PathBuf::from))
|
||||
.map(|path| match crate::platform::binary_kind(&path) {
|
||||
crate::platform::Binary::Windows => "windows",
|
||||
crate::platform::Binary::Native => "native",
|
||||
crate::platform::Binary::Script => "script",
|
||||
crate::platform::Binary::Unknown => "unknown",
|
||||
});
|
||||
let kind = if p.archive_exe.is_some() {
|
||||
"zip"
|
||||
} else if p.local_exe.is_some() {
|
||||
@@ -378,6 +393,7 @@ impl App {
|
||||
),
|
||||
custom: p.custom,
|
||||
kind,
|
||||
binary,
|
||||
web_url: (kind == "git" && (web.starts_with("https://") || web.starts_with("http://")))
|
||||
.then_some(web),
|
||||
listing: p.listing.clone(),
|
||||
@@ -419,7 +435,9 @@ impl App {
|
||||
return *installed;
|
||||
}
|
||||
}
|
||||
let installed = p.archive_program().is_some_and(|exe| exe.is_file())
|
||||
let installed = p
|
||||
.archive_program()
|
||||
.is_some_and(|exe| crate::platform::is_program(&exe))
|
||||
|| p.local_exe
|
||||
.as_deref()
|
||||
.is_some_and(|exe| Path::new(exe).is_file())
|
||||
|
||||
+71
-18
@@ -16,6 +16,7 @@ mod job_log;
|
||||
mod launcher;
|
||||
mod notify;
|
||||
mod patches;
|
||||
mod platform;
|
||||
mod previous;
|
||||
mod report;
|
||||
mod rust_project;
|
||||
@@ -77,6 +78,8 @@ fn log(from: usize, state: tauri::State<'_, Shared>) -> launcher::LogView {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Finder and the Dock give an app a bare PATH; the tools live elsewhere.
|
||||
platform::init_environment();
|
||||
// Fix and verify without a window, for the agent tool (scripts\vilauncher-agent.mjs fix):
|
||||
// `--fix <repo>` prints the job's log and a STAGE line. Debug and release builds alike.
|
||||
// It refuses (exit 1) unless AI agent access is on, and while another launcher window runs.
|
||||
@@ -113,8 +116,7 @@ fn main() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
}
|
||||
}
|
||||
// Development check without a window: the launcher's first snapshot, as JSON.
|
||||
#[cfg(debug_assertions)]
|
||||
// Check without a window: the launcher's first snapshot, as JSON.
|
||||
if std::env::args().any(|a| a == "--dump-snapshot") {
|
||||
let mut app = App::new(notify::Ctx::new(|| {}), settings_store::load());
|
||||
for tries in 0..40 {
|
||||
@@ -138,6 +140,10 @@ fn main() {
|
||||
.plugin(tauri_plugin_window_state::Builder::default().build())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.setup(|tauri_app| {
|
||||
// WKWebView has no edit shortcuts of its own: Cmd+C/V/X/A/Z and
|
||||
// Cmd+Q/H/W only work through a native menu with these items.
|
||||
#[cfg(target_os = "macos")]
|
||||
install_macos_menu(&tauri_app.handle().clone())?;
|
||||
let handle = tauri_app.handle().clone();
|
||||
let ctx = notify::Ctx::new(move || {
|
||||
let _ = handle.emit("launcher://changed", ());
|
||||
@@ -183,24 +189,71 @@ fn fix_allowed() -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a VILauncher.exe other than this process runs (checked with tasklist, CSV: "name","pid",...).
|
||||
/// The macOS application menu: App (about, services, hide, quit), Edit
|
||||
/// (undo, redo, cut, copy, paste, select all) and Window (minimise, zoom,
|
||||
/// close). Without it, the standard keyboard shortcuts do nothing.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn install_macos_menu(app: &tauri::AppHandle) -> tauri::Result<()> {
|
||||
use tauri::menu::{AboutMetadata, Menu, PredefinedMenuItem, Submenu};
|
||||
|
||||
let name = brand::NAME;
|
||||
let app_menu = Submenu::with_items(
|
||||
app,
|
||||
name,
|
||||
true,
|
||||
&[
|
||||
&PredefinedMenuItem::about(
|
||||
app,
|
||||
Some(&format!("About {name}")),
|
||||
Some(AboutMetadata::default()),
|
||||
)?,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&PredefinedMenuItem::services(app, None)?,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&PredefinedMenuItem::hide(app, Some(&format!("Hide {name}")))?,
|
||||
&PredefinedMenuItem::hide_others(app, None)?,
|
||||
&PredefinedMenuItem::show_all(app, None)?,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&PredefinedMenuItem::quit(app, Some(&format!("Quit {name}")))?,
|
||||
],
|
||||
)?;
|
||||
let edit = Submenu::with_items(
|
||||
app,
|
||||
"Edit",
|
||||
true,
|
||||
&[
|
||||
&PredefinedMenuItem::undo(app, None)?,
|
||||
&PredefinedMenuItem::redo(app, None)?,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&PredefinedMenuItem::cut(app, None)?,
|
||||
&PredefinedMenuItem::copy(app, None)?,
|
||||
&PredefinedMenuItem::paste(app, None)?,
|
||||
&PredefinedMenuItem::select_all(app, None)?,
|
||||
],
|
||||
)?;
|
||||
let window = Submenu::with_items(
|
||||
app,
|
||||
"Window",
|
||||
true,
|
||||
&[
|
||||
&PredefinedMenuItem::minimize(app, None)?,
|
||||
&PredefinedMenuItem::maximize(app, Some("Zoom"))?,
|
||||
&PredefinedMenuItem::separator(app)?,
|
||||
&PredefinedMenuItem::close_window(app, None)?,
|
||||
],
|
||||
)?;
|
||||
let menu = Menu::with_items(app, &[&app_menu, &edit, &window])?;
|
||||
app.set_menu(menu)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether another launcher runs besides this process (tasklist on Windows, ps on macOS).
|
||||
/// A `--dump-snapshot` run is a check, not a window, so it never counts as one.
|
||||
fn other_launcher_running() -> Result<bool, String> {
|
||||
let mut command = std::process::Command::new("tasklist");
|
||||
command.args(["/FI", "IMAGENAME eq VILauncher.exe", "/FO", "CSV", "/NH"]);
|
||||
hide_window(&mut command);
|
||||
let output = command
|
||||
.output()
|
||||
.map_err(|_| "could not check whether VILauncher is running (tasklist failed), so Fix was not started".to_string())?;
|
||||
if !output.status.success() {
|
||||
return Err("could not check whether VILauncher is running (tasklist failed), so Fix was not started".into());
|
||||
if std::env::args().any(|a| a == "--dump-snapshot") {
|
||||
return Ok(false);
|
||||
}
|
||||
let me = std::process::id();
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
Ok(text
|
||||
.lines()
|
||||
.filter_map(|line| line.split(',').nth(1))
|
||||
.filter_map(|pid| pid.trim().trim_matches('"').parse::<u32>().ok())
|
||||
.any(|pid| pid != me))
|
||||
platform::other_launcher_running(std::process::id())
|
||||
}
|
||||
|
||||
/// The system's own glass behind the window: Mica on Windows 11 (Acrylic on
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
//! macOS: the `PATH` a GUI app does not get, Finder (`open`), `kill`,
|
||||
//! `df`, `/Volumes`, and the quarantine flag.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The folders the build tools are installed to. A window started from
|
||||
/// Finder gets `/usr/bin:/bin:/usr/sbin:/sbin` only, so these are added to
|
||||
/// every spawned command's `PATH` (see `platform::with_tool_dirs`).
|
||||
pub(super) fn tool_dirs() -> Vec<PathBuf> {
|
||||
let home = std::env::var_os("HOME").map(PathBuf::from);
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
if let Some(home) = home {
|
||||
dirs.push(home.join(".cargo").join("bin"));
|
||||
dirs.push(home.join(".local").join("bin"));
|
||||
dirs.push(
|
||||
home.join(".rustup")
|
||||
.join("toolchains")
|
||||
.join("stable-aarch64-apple-darwin")
|
||||
.join("bin"),
|
||||
);
|
||||
}
|
||||
dirs.push(PathBuf::from("/opt/homebrew/bin"));
|
||||
dirs.push(PathBuf::from("/opt/homebrew/sbin"));
|
||||
dirs.push(PathBuf::from("/usr/local/bin"));
|
||||
dirs.push(PathBuf::from("/Library/Developer/CommandLineTools/usr/bin"));
|
||||
dirs.push(PathBuf::from("/usr/bin"));
|
||||
dirs.push(PathBuf::from("/bin"));
|
||||
dirs.retain(|dir| dir.is_dir());
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The user's login shell.
|
||||
fn user_shell() -> PathBuf {
|
||||
std::env::var_os("SHELL")
|
||||
.map(PathBuf::from)
|
||||
.filter(|shell| shell.is_absolute() && shell.is_file())
|
||||
.unwrap_or_else(|| PathBuf::from("/bin/zsh"))
|
||||
}
|
||||
|
||||
/// Runs a short command and gives up after `limit`: a heavy shell start-up
|
||||
/// must never hold the launcher's start.
|
||||
fn output_within(mut command: Command, limit: Duration) -> Option<Output> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let (send, receive) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let output = command.output();
|
||||
let _ = send.send(output.ok());
|
||||
});
|
||||
receive.recv_timeout(limit).ok()??.into()
|
||||
}
|
||||
|
||||
/// The `PATH` the user's login shell sets, as `-lc` (non-interactive: an
|
||||
/// interactive shell waits for a TTY) with a hard two-second limit, then
|
||||
/// `/usr/libexec/path_helper` when the shell printed nothing usable.
|
||||
fn login_path() -> Option<OsString> {
|
||||
let mut shell = Command::new(user_shell());
|
||||
shell.args(["-lc", "printf %s \"$PATH\""]);
|
||||
if let Some(output) = output_within(shell, Duration::from_secs(2)) {
|
||||
if let Some(path) = path_line(&String::from_utf8_lossy(&output.stdout)) {
|
||||
return Some(OsString::from(path));
|
||||
}
|
||||
}
|
||||
// Apple's own tool: prints `PATH="..."; export PATH;`.
|
||||
let mut helper = Command::new("/usr/libexec/path_helper");
|
||||
helper.arg("-s");
|
||||
let output = output_within(helper, Duration::from_secs(2))?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let line = text
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix("PATH=\""))?
|
||||
.split('"')
|
||||
.next()?;
|
||||
path_line(line).map(OsString::from)
|
||||
}
|
||||
|
||||
/// The `PATH` in a shell's output: start-up files sometimes print, so take
|
||||
/// the last line that looks like a path list.
|
||||
fn path_line(text: &str) -> Option<String> {
|
||||
let line = text
|
||||
.lines()
|
||||
.rev()
|
||||
.map(str::trim)
|
||||
.find(|line| line.contains('/') && !line.contains(' '))?;
|
||||
let valid = line.split(':').filter(|part| part.starts_with('/')).count();
|
||||
(valid > 0).then(|| line.to_owned())
|
||||
}
|
||||
|
||||
/// `PATH` with the tools' folders and the login shell's first, then the one
|
||||
/// the app was started with.
|
||||
pub(super) fn resolved_path(current: Option<OsString>) -> Option<OsString> {
|
||||
let mut dirs = tool_dirs();
|
||||
if let Some(login) = login_path() {
|
||||
dirs.extend(std::env::split_paths(&login));
|
||||
}
|
||||
if let Some(path) = current {
|
||||
dirs.extend(std::env::split_paths(&path));
|
||||
}
|
||||
dirs.retain(|dir| dir.is_absolute());
|
||||
dirs.dedup();
|
||||
std::env::join_paths(dirs).ok()
|
||||
}
|
||||
|
||||
/// Opens a link in the default browser.
|
||||
pub(super) fn open_url(url: &str) -> Result<(), String> {
|
||||
Command::new("/usr/bin/open")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open the link: {error}"))
|
||||
}
|
||||
|
||||
/// Opens a folder in Finder.
|
||||
pub(super) fn open_folder(path: &Path) -> Result<(), String> {
|
||||
Command::new("/usr/bin/open")
|
||||
.arg(path)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open {}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// Reveals a file or folder, selected, in Finder.
|
||||
pub(super) fn reveal(path: &Path) -> Result<(), String> {
|
||||
Command::new("/usr/bin/open")
|
||||
.args(["-R"])
|
||||
.arg(path)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not show {}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// Free bytes on the volume holding `dir`, from `df`.
|
||||
pub(super) fn free_bytes(dir: &Path) -> Option<u64> {
|
||||
let output = Command::new("/bin/df")
|
||||
.args(["-Pk"])
|
||||
.arg(dir)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let line = text.lines().nth(1)?;
|
||||
let available: u64 = line.split_whitespace().nth(3)?.parse().ok()?;
|
||||
available.checked_mul(1024)
|
||||
}
|
||||
|
||||
/// Every process whose program lives under `dir`.
|
||||
fn pids_under(dir: &Path) -> Vec<u32> {
|
||||
let mut command = Command::new("/bin/ps");
|
||||
command.args(["-axo", "pid=,comm="]);
|
||||
let Ok(output) = command.output() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let folder = dir.to_string_lossy();
|
||||
let folder = folder.trim_end_matches('/');
|
||||
let me = std::process::id();
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim_start();
|
||||
let (pid, command) = line.split_once(char::is_whitespace)?;
|
||||
let pid: u32 = pid.parse().ok()?;
|
||||
let command = command.trim();
|
||||
(pid != me && (command == folder || command.starts_with(&format!("{folder}/"))))
|
||||
.then_some(pid)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ends every process running from `dir`, so it can be deleted.
|
||||
pub(super) fn stop_programs_under(dir: &Path) {
|
||||
for pid in pids_under(dir) {
|
||||
signal(pid, "-TERM");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
for pid in pids_under(dir) {
|
||||
signal(pid, "-KILL");
|
||||
}
|
||||
}
|
||||
|
||||
fn signal(pid: u32, name: &str) {
|
||||
let _ = Command::new("/bin/kill")
|
||||
.args([name, &pid.to_string()])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
}
|
||||
|
||||
/// A polite close first, so the game can save; forced only if it is still
|
||||
/// there a few seconds later.
|
||||
pub(super) fn stop_program(pid: u32) {
|
||||
std::thread::spawn(move || {
|
||||
signal(pid, "-TERM");
|
||||
std::thread::sleep(Duration::from_secs(8));
|
||||
signal(pid, "-KILL");
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether another launcher window runs besides `me`.
|
||||
pub(super) fn other_launcher_running(me: u32) -> Result<bool, String> {
|
||||
// `comm` is the program's path, so compare the file name only, and leave
|
||||
// this process out: a dump or a fix run must not count itself.
|
||||
let name = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|exe| exe.file_name().map(|name| name.to_owned()))
|
||||
.unwrap_or_default();
|
||||
let output = Command::new("/bin/ps")
|
||||
.args(["-A", "-o", "pid=,comm="])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.map_err(|_| {
|
||||
"could not check whether VILauncher is running (ps failed), so Fix was not started"
|
||||
.to_string()
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
return Err(
|
||||
"could not check whether VILauncher is running (ps failed), so Fix was not started"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
Ok(text.lines().any(|line| {
|
||||
let line = line.trim();
|
||||
let (pid, command) = match line.split_once(char::is_whitespace) {
|
||||
Some((pid, command)) => (pid, command.trim()),
|
||||
None => return false,
|
||||
};
|
||||
let same_name = Path::new(command)
|
||||
.file_name()
|
||||
.is_some_and(|found| found == name);
|
||||
same_name && pid.parse::<u32>().ok().is_some_and(|pid| pid != me)
|
||||
}))
|
||||
}
|
||||
|
||||
/// A time as the player's clock shows it.
|
||||
pub(super) fn local_time(seconds: u64) -> Option<String> {
|
||||
let output = Command::new("/bin/date")
|
||||
.args(["-r", &seconds.to_string(), "+%Y-%m-%d %H:%M"])
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())
|
||||
}
|
||||
|
||||
/// The game is searched under the mounted volumes and the home folder.
|
||||
pub(super) fn game_search_roots() -> Vec<PathBuf> {
|
||||
let mut roots: Vec<PathBuf> = Vec::new();
|
||||
if let Ok(entries) = std::fs::read_dir("/Volumes") {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
roots.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
roots.push(PathBuf::from(home));
|
||||
}
|
||||
roots.push(PathBuf::from("/Users/Shared"));
|
||||
roots.retain(|root| root.is_dir());
|
||||
roots
|
||||
}
|
||||
|
||||
/// The saved folder under every mounted volume, for a volume that came back
|
||||
/// under another name (its first component is the volume's name).
|
||||
pub(super) fn moved_folder_candidates(saved: &Path, tail: &Path) -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
if let Ok(entries) = std::fs::read_dir("/Volumes") {
|
||||
for entry in entries.flatten() {
|
||||
candidates.push(entry.path().join(tail));
|
||||
}
|
||||
}
|
||||
// The home folder, if the game lived outside a volume mount.
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
let home = PathBuf::from(home);
|
||||
if let Ok(rest) = saved.strip_prefix(&home) {
|
||||
candidates.push(home.join(rest));
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Whether the volume a folder is on is mounted. `/Volumes/<name>` must
|
||||
/// exist; anything outside `/Volumes` is on the boot volume.
|
||||
pub(super) fn drive_connected(dir: &Path) -> bool {
|
||||
let mut parts = dir.components();
|
||||
if parts.next().is_some_and(|c| c == Component::RootDir)
|
||||
&& parts.next().is_some_and(|c| c.as_os_str() == "Volumes")
|
||||
{
|
||||
if let Some(volume) = parts.next() {
|
||||
return Path::new("/Volumes").join(volume).exists();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether Xcode Command Line Tools are installed: `xcode-select -p` answers
|
||||
/// with a path that holds the SDKs, and `clang` answers.
|
||||
pub(super) fn build_tools_installed() -> bool {
|
||||
let output = Command::new("/usr/bin/xcode-select")
|
||||
.arg("-p")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output();
|
||||
let Ok(output) = output else {
|
||||
return false;
|
||||
};
|
||||
if !output.status.success() {
|
||||
return false;
|
||||
}
|
||||
// A path left behind by a removed install is not an install.
|
||||
let path = String::from_utf8_lossy(&output.stdout).trim().to_owned();
|
||||
if !PathBuf::from(&path).is_dir() {
|
||||
return false;
|
||||
}
|
||||
// The full Xcode and the Command Line Tools keep the compiler in different
|
||||
// places, so ask the system for it rather than guess a folder.
|
||||
Command::new("/usr/bin/xcrun")
|
||||
.args(["--find", "clang"])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.map(|found| {
|
||||
found.status.success()
|
||||
&& PathBuf::from(String::from_utf8_lossy(&found.stdout).trim()).is_file()
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the quarantine flag is still on `path`.
|
||||
pub(super) fn is_quarantined(path: &Path) -> bool {
|
||||
Command::new("/usr/bin/xattr")
|
||||
.args(["-p", "com.apple.quarantine"])
|
||||
.arg(path)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Clears the quarantine flag from `path` and everything under it.
|
||||
pub(super) fn clear_quarantine(path: &Path) -> bool {
|
||||
if !is_quarantined(path) {
|
||||
return false;
|
||||
}
|
||||
Command::new("/usr/bin/xattr")
|
||||
.args(["-d", "-r", "com.apple.quarantine"])
|
||||
.arg(path)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map(|status| status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tools_folders_are_all_absolute_and_existing() {
|
||||
for dir in tool_dirs() {
|
||||
assert!(dir.is_absolute(), "{}", dir.display());
|
||||
assert!(dir.is_dir(), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolved_path_starts_with_the_tools_and_keeps_what_was_there() {
|
||||
let path = resolved_path(Some(OsString::from("/custom/bin"))).unwrap();
|
||||
let parts: Vec<PathBuf> = std::env::split_paths(&path).collect();
|
||||
assert!(parts.contains(&PathBuf::from("/usr/bin")));
|
||||
assert_eq!(parts.last(), Some(&PathBuf::from("/custom/bin")));
|
||||
assert!(parts.iter().all(|p| p.is_absolute()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_line_is_taken_from_noisy_shell_output() {
|
||||
let text = "Restored session: Nov 27\n/Users/someone/.cargo/bin:/usr/bin:/bin";
|
||||
assert_eq!(
|
||||
path_line(text).as_deref(),
|
||||
Some("/Users/someone/.cargo/bin:/usr/bin:/bin")
|
||||
);
|
||||
assert!(path_line("Welcome back!").is_none());
|
||||
assert!(path_line("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_outside_volumes_is_on_the_boot_disk() {
|
||||
assert!(drive_connected(Path::new("/Users/someone/Games")));
|
||||
assert!(!drive_connected(Path::new(
|
||||
"/Volumes/No Such Volume Here/Games"
|
||||
)));
|
||||
assert!(drive_connected(Path::new("/Volumes")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
//! What differs between the systems the launcher runs on: hiding consoles,
|
||||
//! finding the tools on a GUI's short `PATH`, opening links and folders,
|
||||
//! ending programs, reading free space, and finding the game on other drives
|
||||
//! or volumes.
|
||||
//!
|
||||
//! Everything the rest of the launcher calls lives here, so no other module
|
||||
//! needs a `#[cfg]` for these jobs. The Windows behaviour is unchanged.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
/// Whether a spawned program gets a console window. Windows: never (a
|
||||
/// detached console would flash); elsewhere a console is not a thing.
|
||||
pub(crate) fn configure_background_command(c: &mut Command) {
|
||||
#[cfg(windows)]
|
||||
windows::hide_window(c);
|
||||
#[cfg(not(windows))]
|
||||
let _ = c;
|
||||
}
|
||||
|
||||
/// The folders the build tools are installed to. Empty on Windows (its
|
||||
/// installers write the `PATH` themselves).
|
||||
pub(crate) fn tool_dirs() -> Vec<PathBuf> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::tool_dirs()
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// `PATH` with the tools' folders first, then what was already there.
|
||||
/// Used by every spawned command, so a `PATH` changed after the launcher
|
||||
/// started still reaches `git`, `cargo` and the game.
|
||||
pub(crate) fn with_tool_dirs(existing: Option<std::ffi::OsString>) -> Option<std::ffi::OsString> {
|
||||
let mut dirs = tool_dirs();
|
||||
if let Some(path) = existing.as_ref() {
|
||||
dirs.extend(std::env::split_paths(path).filter(|d| !d.as_os_str().is_empty()));
|
||||
}
|
||||
if dirs.is_empty() {
|
||||
return existing;
|
||||
}
|
||||
dirs.dedup();
|
||||
std::env::join_paths(dirs).ok().or(existing)
|
||||
}
|
||||
|
||||
/// Gives this process (and so every program it starts) the folders the
|
||||
/// tools live in. macOS apps started from Finder, Spotlight or the Dock get
|
||||
/// `/usr/bin:/bin:/usr/sbin:/sbin` only and would not find cargo, rustc or a
|
||||
/// Homebrew git; the user's login shell knows better.
|
||||
pub(crate) fn init_environment() {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let current = std::env::var_os("PATH");
|
||||
if let Some(path) = macos::resolved_path(current.clone()) {
|
||||
std::env::set_var("PATH", path);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = std::env::var_os("PATH");
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens an `https` link in the player's browser.
|
||||
pub(crate) fn open_url(url: &str) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Explorer takes the link as one argument; no shell, so nothing in it is re-parsed.
|
||||
Command::new("explorer.exe")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open the link: {error}"))
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::open_url(url)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
Command::new("xdg-open")
|
||||
.arg(url)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open the link: {error}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a folder in the system's file manager.
|
||||
pub(crate) fn open_folder(path: &Path) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
Command::new("explorer")
|
||||
.arg(path)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open {}: {error}", path.display()))
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::open_folder(path)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
Command::new("xdg-open")
|
||||
.arg(path)
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not open {}: {error}", path.display()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a file or folder selected in the file manager (Finder: "Reveal").
|
||||
pub(crate) fn reveal(path: &Path) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::reveal(path)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
// Windows' Explorer selects with `/select,`; the folder itself is opened otherwise.
|
||||
if path.is_dir() {
|
||||
open_folder(path)
|
||||
} else {
|
||||
Command::new("explorer")
|
||||
.arg(format!("/select,{}", path.display()))
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("Could not show {}: {error}", path.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Free bytes on the disk holding `dir`. `None` when it cannot be read.
|
||||
pub(crate) fn free_bytes(dir: &Path) -> Option<u64> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::free_bytes(dir)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::free_bytes(dir)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = dir;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends every program running from a folder (the game and the runner), so an
|
||||
/// uninstall or a rollback can delete it.
|
||||
pub(crate) fn stop_programs_under(dir: &Path) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::stop_programs_under(dir);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::stop_programs_under(dir);
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = dir;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends one program: a polite close first so the game can save, a forced one
|
||||
/// seconds later if it is still there. Never blocks the caller.
|
||||
pub(crate) fn stop_program(pid: u32) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::stop_program(pid);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::stop_program(pid);
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = pid;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether another launcher window runs besides this process.
|
||||
pub(crate) fn other_launcher_running(me: u32) -> Result<bool, String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::other_launcher_running(me)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::other_launcher_running(me)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = me;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// A time as the player's clock shows it. `None` where it cannot be read.
|
||||
pub(crate) fn local_time(seconds: u64) -> Option<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
crate::build_activity::local_time(seconds)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::local_time(seconds)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = seconds;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots a search for the game walks: drive letters on Windows, mounted
|
||||
/// volumes and the home folder on macOS.
|
||||
pub(crate) fn game_search_roots() -> Vec<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::game_search_roots()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::game_search_roots()
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
vec![PathBuf::from("/")]
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a saved folder may be if its drive letter or volume name changed.
|
||||
pub(crate) fn moved_folder_candidates(saved: &Path, tail: &Path) -> Vec<PathBuf> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::moved_folder_candidates(saved, tail)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::moved_folder_candidates(saved, tail)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = saved;
|
||||
vec![PathBuf::from("/").join(tail)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the disk a folder is on is connected. A relative folder counts as
|
||||
/// connected.
|
||||
pub(crate) fn drive_connected(dir: &Path) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::drive_connected(dir)
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::drive_connected(dir)
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = dir;
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a Cargo binary target gets on this system.
|
||||
pub(crate) fn exe_name(stem: &str) -> String {
|
||||
if cfg!(windows) {
|
||||
format!("{stem}.exe")
|
||||
} else {
|
||||
stem.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of program a file is: a Windows PE, a native Mach-O, a script, or
|
||||
/// something else. Used to tell a player that a prebuilt ZIP is Windows-only.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Binary {
|
||||
Windows,
|
||||
Native,
|
||||
Script,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Reads the first bytes of `path`. Never panics; an unreadable file is `Unknown`.
|
||||
pub(crate) fn binary_kind(path: &Path) -> Binary {
|
||||
use std::io::Read;
|
||||
let Ok(mut file) = std::fs::File::open(path) else {
|
||||
return Binary::Unknown;
|
||||
};
|
||||
let mut magic = [0u8; 4];
|
||||
let read = file.read(&mut magic).unwrap_or(0);
|
||||
if read >= 2 && &magic[..2] == b"MZ" {
|
||||
return Binary::Windows;
|
||||
}
|
||||
if read >= 2 && &magic[..2] == b"#!" {
|
||||
return Binary::Script;
|
||||
}
|
||||
if read == 4 {
|
||||
let m = u32::from_be_bytes(magic);
|
||||
// Mach-O thin (both byte orders, 32 and 64 bit) and universal ("fat") images.
|
||||
if matches!(
|
||||
m,
|
||||
0xfeed_face | 0xfeed_facf | 0xcefa_edfe | 0xcffa_edfe | 0xcafe_babe | 0xbeba_feca
|
||||
) {
|
||||
return Binary::Native;
|
||||
}
|
||||
}
|
||||
if read == 4 {
|
||||
let m = u32::from_le_bytes(magic);
|
||||
if matches!(m, 0xfeed_face | 0xfeed_facf) {
|
||||
return Binary::Native;
|
||||
}
|
||||
}
|
||||
Binary::Unknown
|
||||
}
|
||||
|
||||
/// Whether `path` is the program, a bundle, or a folder holding it: the thing
|
||||
/// to run. A macOS `.app` runs its own program with the arguments and
|
||||
/// environment the caller set, so its output is still captured.
|
||||
pub(crate) fn program_for(path: &Path) -> (PathBuf, Option<PathBuf>) {
|
||||
if path.extension().is_some_and(|ext| ext == "app") && path.is_dir() {
|
||||
let macos = path.join("Contents").join("MacOS");
|
||||
if let Ok(entries) = std::fs::read_dir(&macos) {
|
||||
if let Some(found) = entries.flatten().map(|e| e.path()).find(|p| p.is_file()) {
|
||||
return (found, Some(macos));
|
||||
}
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), path.parent().map(Path::to_path_buf))
|
||||
}
|
||||
|
||||
/// Whether the C++ build tools (Windows) or Xcode Command Line Tools
|
||||
/// (macOS) are installed: Rust needs their linker.
|
||||
pub(crate) fn build_tools_installed() -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::build_tools_installed()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::build_tools_installed()
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
// A linker from the system's packages is assumed present.
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is something that can be started: a file, or a `.app` bundle.
|
||||
pub(crate) fn is_program(path: &Path) -> bool {
|
||||
path.is_file() || (path.extension().is_some_and(|ext| ext == "app") && path.is_dir())
|
||||
}
|
||||
|
||||
/// Adds the execute bit after unpacking, where the system has one.
|
||||
pub(crate) fn make_executable(path: &Path) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if let Ok(meta) = std::fs::metadata(path) {
|
||||
let mut permissions = meta.permissions();
|
||||
permissions.set_mode(permissions.mode() | 0o755);
|
||||
let _ = std::fs::set_permissions(path, permissions);
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
}
|
||||
|
||||
/// Clears macOS's quarantine flag from a freshly unpacked folder, where it is
|
||||
/// set. Gatekeeper would otherwise refuse the game the first time.
|
||||
pub(crate) fn clear_quarantine(path: &Path) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::clear_quarantine(path)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` still carries the quarantine flag.
|
||||
pub(crate) fn is_quarantined(path: &Path) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::is_quarantined(path)
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"vilauncher-platform-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binaries_are_recognised_by_their_first_bytes() {
|
||||
let dir = temp("kind");
|
||||
let pe = dir.join("a.exe");
|
||||
std::fs::write(&pe, b"MZ\x90\x00rest").unwrap();
|
||||
assert_eq!(binary_kind(&pe), Binary::Windows);
|
||||
let macho = dir.join("a");
|
||||
std::fs::write(&macho, [0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0]).unwrap();
|
||||
assert_eq!(binary_kind(&macho), Binary::Native);
|
||||
let fat = dir.join("b");
|
||||
std::fs::write(&fat, [0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0]).unwrap();
|
||||
assert_eq!(binary_kind(&fat), Binary::Native);
|
||||
let script = dir.join("c.sh");
|
||||
std::fs::write(&script, b"#!/bin/sh\n").unwrap();
|
||||
assert_eq!(binary_kind(&script), Binary::Script);
|
||||
let other = dir.join("d.txt");
|
||||
std::fs::write(&other, b"hello").unwrap();
|
||||
assert_eq!(binary_kind(&other), Binary::Unknown);
|
||||
assert_eq!(binary_kind(&dir.join("missing")), Binary::Unknown);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bundle_runs_the_program_inside_it() {
|
||||
let dir = temp("bundle");
|
||||
let app = dir.join("Game.app");
|
||||
let macos = app.join("Contents").join("MacOS");
|
||||
std::fs::create_dir_all(&macos).unwrap();
|
||||
std::fs::write(macos.join("game"), b"x").unwrap();
|
||||
let (program, cwd) = program_for(&app);
|
||||
assert_eq!(program, macos.join("game"));
|
||||
assert_eq!(cwd, Some(macos));
|
||||
let plain = dir.join("victory");
|
||||
std::fs::write(&plain, b"x").unwrap();
|
||||
assert_eq!(program_for(&plain), (plain.clone(), Some(dir.clone())));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exe_suffix_follows_the_system() {
|
||||
let name = exe_name("victory");
|
||||
if cfg!(windows) {
|
||||
assert_eq!(name, "victory.exe");
|
||||
} else {
|
||||
assert_eq!(name, "victory");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Windows: console hiding, `taskkill`/`tasklist`, drive letters, `fsutil`.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// Runs a program without its console window flashing up.
|
||||
pub(super) fn hide_window(c: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
c.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
/// Free bytes on the volume holding `dir`, read with `fsutil`.
|
||||
pub(super) fn free_bytes(dir: &Path) -> Option<u64> {
|
||||
let drive: String = dir
|
||||
.components()
|
||||
.take(2)
|
||||
.collect::<PathBuf>()
|
||||
.display()
|
||||
.to_string();
|
||||
let mut c = Command::new("fsutil");
|
||||
c.args(["volume", "diskfree", &drive]);
|
||||
hide_window(&mut c);
|
||||
let output = c.output().ok()?;
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
let after = text.lines().next()?.split(':').nth(1)?;
|
||||
let digits: String = after
|
||||
.split('(')
|
||||
.next()?
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_digit())
|
||||
.collect();
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
/// Ends every process whose program lives under `dir` (the game and the runner).
|
||||
pub(super) fn stop_programs_under(dir: &Path) {
|
||||
let folder = dir.display().to_string().replace('\'', "''");
|
||||
let script = format!(
|
||||
"Get-Process | Where-Object {{ $_.Path -and $_.Path.StartsWith('{folder}', [StringComparison]::OrdinalIgnoreCase) }} | Stop-Process -Force -ErrorAction SilentlyContinue"
|
||||
);
|
||||
let mut c = Command::new("powershell");
|
||||
c.args(["-NoProfile", "-NonInteractive", "-Command", &script]);
|
||||
hide_window(&mut c);
|
||||
let _ = c.status();
|
||||
}
|
||||
|
||||
/// A window close first, so the game can save; forced only if it is still
|
||||
/// running a few seconds later.
|
||||
pub(super) fn stop_program(pid: u32) {
|
||||
std::thread::spawn(move || {
|
||||
let pid = pid.to_string();
|
||||
let mut close = Command::new("taskkill");
|
||||
close.args(["/PID", &pid, "/T"]);
|
||||
hide_window(&mut close);
|
||||
let _ = close.status();
|
||||
std::thread::sleep(std::time::Duration::from_secs(8));
|
||||
let mut force = Command::new("taskkill");
|
||||
force.args(["/PID", &pid, "/T", "/F"]);
|
||||
hide_window(&mut force);
|
||||
let _ = force.status();
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a VILauncher other than `me` runs, from tasklist's CSV output.
|
||||
pub(super) fn other_launcher_running(me: u32) -> Result<bool, String> {
|
||||
let mut command = Command::new("tasklist");
|
||||
command.args(["/FI", "IMAGENAME eq VILauncher.exe", "/FO", "CSV", "/NH"]);
|
||||
hide_window(&mut command);
|
||||
let output = command.output().map_err(|_| {
|
||||
"could not check whether VILauncher is running (tasklist failed), so Fix was not started"
|
||||
.to_string()
|
||||
})?;
|
||||
if !output.status.success() {
|
||||
return Err("could not check whether VILauncher is running (tasklist failed), so Fix was not started".into());
|
||||
}
|
||||
let text = String::from_utf8_lossy(&output.stdout);
|
||||
Ok(text
|
||||
.lines()
|
||||
.filter_map(|line| line.split(',').nth(1))
|
||||
.filter_map(|pid| pid.trim().trim_matches('"').parse::<u32>().ok())
|
||||
.any(|pid| pid != me))
|
||||
}
|
||||
|
||||
/// Every connected drive, C: to Z:.
|
||||
pub(super) fn game_search_roots() -> Vec<PathBuf> {
|
||||
(b'C'..=b'Z')
|
||||
.map(|letter| PathBuf::from(format!("{}:\\", letter as char)))
|
||||
.filter(|root| root.is_dir())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The same folder on another drive (an external SSD that came back as F:
|
||||
/// instead of E:), for a folder whose drive letter changed.
|
||||
pub(super) fn moved_folder_candidates(_saved: &Path, tail: &Path) -> Vec<PathBuf> {
|
||||
(b'A'..=b'Z')
|
||||
.map(|letter| PathBuf::from(format!("{}:\\", letter as char)))
|
||||
.map(|root| root.join(tail))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the drive a folder is on is connected. A folder without a drive
|
||||
/// letter counts as connected.
|
||||
pub(super) fn drive_connected(dir: &Path) -> bool {
|
||||
match dir.components().next() {
|
||||
Some(Component::Prefix(_)) => dir.components().take(2).collect::<PathBuf>().exists(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a Visual Studio install (any edition, Build Tools too) has the
|
||||
/// 64-bit C++ linker.
|
||||
pub(super) fn build_tools_installed() -> bool {
|
||||
fn env_path(var: &str) -> Option<PathBuf> {
|
||||
std::env::var_os(var).map(PathBuf::from)
|
||||
}
|
||||
// Every Visual Studio install, from the installer's own list, else the usual folders.
|
||||
let mut roots: Vec<PathBuf> = Vec::new();
|
||||
if let Some(pf86) = env_path("ProgramFiles(x86)") {
|
||||
let vswhere = pf86
|
||||
.join("Microsoft Visual Studio")
|
||||
.join("Installer")
|
||||
.join("vswhere.exe");
|
||||
if vswhere.is_file() {
|
||||
let mut c = Command::new(vswhere);
|
||||
c.args(["-all", "-products", "*", "-property", "installationPath"]);
|
||||
hide_window(&mut c);
|
||||
if let Ok(o) = c.output() {
|
||||
roots.extend(
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for base in [env_path("ProgramFiles"), env_path("ProgramFiles(x86)")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let vs = base.join("Microsoft Visual Studio");
|
||||
for year in std::fs::read_dir(&vs).into_iter().flatten().flatten() {
|
||||
for edition in std::fs::read_dir(year.path())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
roots.push(edition.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.iter().any(|root| {
|
||||
std::fs::read_dir(root.join("VC").join("Tools").join("MSVC"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|v| {
|
||||
v.path()
|
||||
.join("bin")
|
||||
.join("Hostx64")
|
||||
.join("x64")
|
||||
.join("link.exe")
|
||||
.is_file()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Unused on Windows but kept so both modules have the same helpers.
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn silence(c: &mut Command) {
|
||||
c.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
}
|
||||
@@ -33,6 +33,44 @@ pub(crate) struct Facts<'a> {
|
||||
pub private: Vec<String>,
|
||||
}
|
||||
|
||||
/// Names and folders that must not leave the PC: the user's name, their home
|
||||
/// folder, mounted volumes, the host name and `workspace`, on Windows
|
||||
/// (`C:\Users\alice`) and macOS (`/Users/alice`, `/Volumes/Backup`) alike.
|
||||
pub(crate) fn private_paths(workspace: &std::path::Path) -> Vec<String> {
|
||||
let mut private: Vec<String> = Vec::new();
|
||||
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
|
||||
private.push(home.to_string_lossy().into_owned());
|
||||
}
|
||||
for var in ["USER", "USERNAME", "LOGNAME"] {
|
||||
if let Ok(value) = std::env::var(var) {
|
||||
private.push(value);
|
||||
}
|
||||
}
|
||||
for var in ["COMPUTERNAME", "HOSTNAME"] {
|
||||
if let Ok(value) = std::env::var(var) {
|
||||
private.push(value);
|
||||
}
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
if let Ok(output) = std::process::Command::new("/usr/sbin/scutil")
|
||||
.args(["--get", "ComputerName"])
|
||||
.output()
|
||||
{
|
||||
private.push(String::from_utf8_lossy(&output.stdout).trim().to_owned());
|
||||
}
|
||||
if let Ok(entries) = std::fs::read_dir("/Volumes") {
|
||||
private.extend(
|
||||
entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path().to_string_lossy().into_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
private.push(workspace.to_string_lossy().into_owned());
|
||||
private.retain(|s| !s.trim().is_empty());
|
||||
private
|
||||
}
|
||||
|
||||
/// Removes every private string from `text`, longest first, and with either slash.
|
||||
pub(crate) fn scrub(text: &str, private: &[String]) -> String {
|
||||
let mut secrets: Vec<String> = private
|
||||
@@ -182,6 +220,23 @@ mod tests {
|
||||
assert!(report.launcher_url.len() < 12_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macos_paths_and_names_are_scrubbed() {
|
||||
let private = vec![
|
||||
"/Users/esperance".to_string(),
|
||||
"/Volumes/Backup".to_string(),
|
||||
"esperance".to_string(),
|
||||
"Esperances-MacBook-Pro".to_string(),
|
||||
];
|
||||
let text = "warning in /Users/esperance/Library/Application Support/VILauncher (Esperances-MacBook-Pro)";
|
||||
let scrubbed = scrub(text, &private);
|
||||
assert!(!scrubbed.contains("esperance"), "{scrubbed}");
|
||||
assert!(!scrubbed.contains("/Volumes/Backup"));
|
||||
assert!(scrubbed.contains("<private>"));
|
||||
// The home folder is cut whole, before the bare name can split it.
|
||||
assert!(scrubbed.starts_with("warning in <private>/Library"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scrub_handles_both_slashes_and_longest_first() {
|
||||
let private = vec!["C:\\Users\\alice".to_string(), "alice".to_string()];
|
||||
|
||||
+227
-35
@@ -17,6 +17,9 @@ pub(crate) struct SystemInfo {
|
||||
pub cpu: Option<String>,
|
||||
/// Logical processors (threads), summed over every socket.
|
||||
pub cpu_cores: Option<u32>,
|
||||
/// Running under Rosetta 2 on Apple silicon (a translated process).
|
||||
#[serde(default)]
|
||||
pub translated: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
@@ -94,6 +97,7 @@ fn not_a_card(name: &str) -> bool {
|
||||
"basic render",
|
||||
"hyper-v",
|
||||
"mirror driver",
|
||||
"paravirtual",
|
||||
]
|
||||
.iter()
|
||||
.any(|w| l.contains(w))
|
||||
@@ -139,40 +143,20 @@ fn detect_inner() -> SystemInfo {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn detect_inner() -> SystemInfo {
|
||||
let sysctl = |key: &str| -> Option<String> {
|
||||
let out = std::process::Command::new("/usr/sbin/sysctl")
|
||||
.args(["-n", key])
|
||||
.output()
|
||||
.ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
|
||||
};
|
||||
let ram_gb = sysctl("hw.memsize")
|
||||
.and_then(|s| s.parse::<f64>().ok())
|
||||
.and_then(ram_gb);
|
||||
// Apple silicon: the graphics are part of the chip and share its memory.
|
||||
let cpu = sysctl("machdep.cpu.brand_string");
|
||||
let gpus = cpu
|
||||
.clone()
|
||||
.filter(|chip| chip.starts_with("Apple"))
|
||||
.map(|chip| {
|
||||
vec![Gpu {
|
||||
vendor: vendor(&chip),
|
||||
name: chip,
|
||||
vram_gb: None,
|
||||
}]
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let cpu_cores = sysctl("hw.logicalcpu")
|
||||
.and_then(|s| s.parse::<u32>().ok())
|
||||
.filter(|n| *n >= 1);
|
||||
SystemInfo {
|
||||
gpus,
|
||||
ram_gb,
|
||||
cpu,
|
||||
cpu_cores,
|
||||
}
|
||||
macos::detect()
|
||||
}
|
||||
|
||||
/// The share of unified memory a game can sensibly use: Apple's own
|
||||
/// `recommendedMaxWorkingSetSize` is about three quarters, and the rest of
|
||||
/// the system needs the remainder. Kept shy of it so a Fit warning is not
|
||||
/// given to a build that fits.
|
||||
const UNIFIED_SHARE: f64 = 0.7;
|
||||
|
||||
/// The graphics memory budget to report for a chip with unified memory.
|
||||
fn unified_budget(ram_gb: Option<f64>) -> Option<f64> {
|
||||
let ram = ram_gb?;
|
||||
// Half-gigabyte steps, never less than one.
|
||||
Some(((ram * UNIFIED_SHARE * 2.0).round() / 2.0).max(1.0))
|
||||
}
|
||||
|
||||
#[cfg(all(not(windows), not(target_os = "macos")))]
|
||||
@@ -238,6 +222,7 @@ fn parse_report(json: &str) -> Option<SystemInfo> {
|
||||
ram_gb: ram.and_then(ram_gb),
|
||||
cpu,
|
||||
cpu_cores,
|
||||
translated: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -364,6 +349,212 @@ $cores = [int]((Get-CimInstance Win32_Processor | Measure-Object -Property Numbe
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos {
|
||||
use super::*;
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// One `sysctl` value, trimmed; `None` when the key is unknown.
|
||||
fn sysctl(key: &str) -> Option<String> {
|
||||
let out = Command::new("/usr/sbin/sysctl")
|
||||
.args(["-n", key])
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
/// A "4 GB" / "1536 MB" memory figure in bytes.
|
||||
fn bytes_from_text(text: &str) -> Option<f64> {
|
||||
let number: f64 = text
|
||||
.split_whitespace()
|
||||
.find(|word| word.chars().next().is_some_and(|c| c.is_ascii_digit()))?
|
||||
.trim_end_matches(|c: char| !c.is_ascii_digit())
|
||||
.parse()
|
||||
.ok()?;
|
||||
let unit = text.to_lowercase();
|
||||
let factor = if unit.contains("gb") {
|
||||
GIB
|
||||
} else if unit.contains("mb") {
|
||||
GIB / 1024.0
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some(number * factor)
|
||||
}
|
||||
|
||||
/// The displays `system_profiler` reports: (name, video memory when given).
|
||||
fn parse_displays(json: &str) -> Vec<(String, Option<f64>)> {
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(json) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let list = value["SPDisplaysDataType"]
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
list.iter()
|
||||
.filter_map(|entry| {
|
||||
let name = entry["sppci_model"]
|
||||
.as_str()
|
||||
.or_else(|| entry["_name"].as_str())?
|
||||
.trim()
|
||||
.to_owned();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let memory = [
|
||||
"spdisplays_vram",
|
||||
"spdisplays_vram_shared",
|
||||
"_spdisplays_vram",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|key| entry[*key].as_str().and_then(bytes_from_text));
|
||||
Some((name, memory))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The graphics cards `system_profiler` lists (a couple of seconds; gives
|
||||
/// up after three so a wedged profiler never holds the start).
|
||||
fn displays() -> Vec<(String, Option<f64>)> {
|
||||
let mut c = Command::new("/usr/sbin/system_profiler");
|
||||
c.args(["SPDisplaysDataType", "-json"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
let Ok(mut child) = c.spawn() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut stdout = child.stdout.take().expect("piped");
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut out = String::new();
|
||||
let _ = stdout.read_to_string(&mut out);
|
||||
out
|
||||
});
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if start.elapsed() < Duration::from_secs(3) => {
|
||||
std::thread::sleep(Duration::from_millis(50))
|
||||
}
|
||||
_ => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
}
|
||||
reader
|
||||
.join()
|
||||
.ok()
|
||||
.map(|out| parse_displays(&out))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn detect() -> SystemInfo {
|
||||
let cpu = sysctl("machdep.cpu.brand_string");
|
||||
let ram = sysctl("hw.memsize")
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
.and_then(ram_gb);
|
||||
let translated = sysctl("sysctl.proc_translated").as_deref() == Some("1");
|
||||
let cpu_cores = sysctl("hw.logicalcpu")
|
||||
.or_else(|| sysctl("hw.ncpu"))
|
||||
.and_then(|value| value.parse::<u32>().ok())
|
||||
.filter(|n| *n >= 1);
|
||||
// A whole-chip Apple GPU shares the system's memory; a discrete or
|
||||
// Intel Mac card has its own and is read from `system_profiler`.
|
||||
let gpus = match cpu.clone().filter(|chip| chip.starts_with("Apple")) {
|
||||
Some(chip) => vec![Gpu {
|
||||
name: format!("{chip} (Unified Memory)"),
|
||||
vendor: Vendor::Apple,
|
||||
vram_gb: unified_budget(ram),
|
||||
}],
|
||||
None => {
|
||||
let found: Vec<Gpu> = displays()
|
||||
.into_iter()
|
||||
.filter(|(name, _)| !not_a_card(name))
|
||||
.map(|(name, bytes)| Gpu {
|
||||
vendor: vendor(&name),
|
||||
name,
|
||||
vram_gb: bytes.and_then(vram_gb),
|
||||
})
|
||||
.collect();
|
||||
// No answer (killed, or a profiler that failed): name the
|
||||
// machine's chip so the fit check still has something to go on.
|
||||
if found.is_empty() {
|
||||
chip_gpu(&sysctl("hw.model")).into_iter().collect()
|
||||
} else {
|
||||
found
|
||||
}
|
||||
}
|
||||
};
|
||||
SystemInfo {
|
||||
gpus,
|
||||
ram_gb: ram,
|
||||
cpu,
|
||||
cpu_cores,
|
||||
translated,
|
||||
}
|
||||
}
|
||||
|
||||
/// The card a fallback can name when `system_profiler` gave nothing: an
|
||||
/// Intel Mac's integrated-graphics family from the model identifier.
|
||||
fn chip_gpu(model: &Option<String>) -> Option<Gpu> {
|
||||
let model = model.as_ref()?;
|
||||
let name = if model.starts_with("MacBookPro1") || model.starts_with("MacBookAir1") {
|
||||
"Intel integrated graphics"
|
||||
} else if model.starts_with("MacPro") || model.starts_with("iMac") {
|
||||
"Graphics"
|
||||
} else {
|
||||
"Unknown graphics"
|
||||
};
|
||||
Some(Gpu {
|
||||
name: name.to_owned(),
|
||||
vendor: Vendor::Other,
|
||||
vram_gb: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displays_are_read_from_the_profiler_report() {
|
||||
let report = r#"{"SPDisplaysDataType":[{"sppci_model":"Apple M3 Pro","spdisplays_vram_shared":"18 GB"},
|
||||
{"_name":"Apple Paravirtual device","spdisplays_vram":"0 MB"},
|
||||
{"sppci_model":"AMD Radeon Pro 5500M","spdisplays_vram":"4 GB"}]}"#;
|
||||
let found = parse_displays(report);
|
||||
assert_eq!(found.len(), 3);
|
||||
assert_eq!(found[0].0, "Apple M3 Pro");
|
||||
assert_eq!(found[0].1, Some(18.0 * GIB));
|
||||
assert_eq!(found[2].1, Some(4.0 * GIB));
|
||||
assert!(parse_displays("not json").is_empty());
|
||||
assert!(parse_displays("{}").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_profiler_answer_still_names_the_graphics() {
|
||||
let Some(gpu) = chip_gpu(&Some("MacBookPro16,1".to_string())) else {
|
||||
panic!("a model identifier names a card")
|
||||
};
|
||||
assert_eq!(gpu.name, "Intel integrated graphics");
|
||||
assert!(chip_gpu(&None).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unified_budget_is_a_share_of_memory_in_half_gigabyte_steps() {
|
||||
assert_eq!(unified_budget(Some(16.0)), Some(11.0)); // 11.2, shy of Apple's 75%
|
||||
assert_eq!(unified_budget(Some(8.0)), Some(5.5));
|
||||
assert_eq!(unified_budget(Some(64.0)), Some(45.0));
|
||||
assert_eq!(unified_budget(None), None);
|
||||
assert!(unified_budget(Some(1.0)).unwrap() >= 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -462,10 +653,11 @@ mod tests {
|
||||
ram_gb: Some(16.0),
|
||||
cpu: Some("Y".into()),
|
||||
cpu_cores: Some(8),
|
||||
translated: false,
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_string(&info).unwrap(),
|
||||
r#"{"gpus":[{"name":"X","vendor":"NVIDIA","vram_gb":null}],"ram_gb":16.0,"cpu":"Y","cpu_cores":8}"#
|
||||
r#"{"gpus":[{"name":"X","vendor":"NVIDIA","vram_gb":null}],"ram_gb":16.0,"cpu":"Y","cpu_cores":8,"translated":false}"#
|
||||
);
|
||||
}
|
||||
}
|
||||
+208
-117
@@ -1,8 +1,10 @@
|
||||
//! Git, Rust (cargo) and the C++ build tools that building a project needs:
|
||||
//! found on the PATH or in the folders their installers use (a PATH changed
|
||||
//! after Windows started does not reach programs started before), and put
|
||||
//! on this PC with winget when the player asks.
|
||||
//! Git, Rust (cargo) and the build tools that building a project needs:
|
||||
//! found on the `PATH` or in the folders their installers use (a `PATH`
|
||||
//! changed after the launcher started does not reach programs started before
|
||||
//! it), and put on this PC with the system's own installer when the player
|
||||
//! asks: winget on Windows, Xcode Command Line Tools and rustup on macOS.
|
||||
|
||||
use crate::platform;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
@@ -11,31 +13,49 @@ use std::sync::Mutex;
|
||||
pub struct Tools {
|
||||
pub git: Option<PathBuf>,
|
||||
pub cargo: Option<PathBuf>,
|
||||
/// The C++ build tools (MSVC): Rust needs their linker.
|
||||
pub msvc: bool,
|
||||
/// The C++ build tools (MSVC) on Windows, Xcode Command Line Tools on
|
||||
/// macOS. Rust needs their linker.
|
||||
pub clt: bool,
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
pub fn ready(&self) -> bool {
|
||||
self.git.is_some() && self.cargo.is_some() && self.msvc
|
||||
self.git.is_some() && self.cargo.is_some() && self.clt
|
||||
}
|
||||
|
||||
/// What is missing, for people.
|
||||
pub fn missing(&self) -> Vec<&'static str> {
|
||||
let mut m = Vec::new();
|
||||
if !self.clt {
|
||||
m.push(BUILD_TOOLS);
|
||||
}
|
||||
if self.git.is_none() {
|
||||
m.push("Git");
|
||||
}
|
||||
if self.cargo.is_none() {
|
||||
m.push("Rust");
|
||||
}
|
||||
if !self.msvc {
|
||||
m.push("C++ build tools");
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// What the build tools are called on this system.
|
||||
#[cfg(windows)]
|
||||
pub const BUILD_TOOLS: &str = "C++ build tools";
|
||||
#[cfg(target_os = "macos")]
|
||||
pub const BUILD_TOOLS: &str = "Xcode Command Line Tools";
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub const BUILD_TOOLS: &str = "build tools";
|
||||
|
||||
/// How the tools are installed here, for the UI's hint.
|
||||
#[cfg(windows)]
|
||||
pub const INSTALL_HINT: &str = "Installs with winget; Windows asks for permission.";
|
||||
#[cfg(target_os = "macos")]
|
||||
pub const INSTALL_HINT: &str =
|
||||
"Uses Apple's Command Line Tools installer and rustup; macOS asks for permission.";
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
pub const INSTALL_HINT: &str = "Installed with the system's package manager.";
|
||||
|
||||
/// The last look, shared with the build commands.
|
||||
static FOUND: Mutex<Option<Tools>> = Mutex::new(None);
|
||||
|
||||
@@ -50,9 +70,10 @@ fn env_path(var: &str) -> Option<PathBuf> {
|
||||
fn answers(program: &Path) -> bool {
|
||||
let mut c = Command::new(program);
|
||||
c.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
crate::hide_window(&mut c);
|
||||
platform::configure_background_command(&mut c);
|
||||
c.status().map(|s| s.success()).unwrap_or(false)
|
||||
}
|
||||
|
||||
@@ -68,71 +89,15 @@ fn find(name: &str, places: &[Option<PathBuf>]) -> Option<PathBuf> {
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn msvc_installed() -> bool {
|
||||
// Every Visual Studio install (any edition, Build Tools too), from the
|
||||
// installer's own list, else the usual folders.
|
||||
let mut roots: Vec<PathBuf> = Vec::new();
|
||||
if let Some(pf86) = env_path("ProgramFiles(x86)") {
|
||||
let vswhere = pf86
|
||||
.join("Microsoft Visual Studio")
|
||||
.join("Installer")
|
||||
.join("vswhere.exe");
|
||||
if vswhere.is_file() {
|
||||
let mut c = Command::new(vswhere);
|
||||
c.args(["-all", "-products", "*", "-property", "installationPath"]);
|
||||
crate::hide_window(&mut c);
|
||||
if let Ok(o) = c.output() {
|
||||
roots.extend(
|
||||
String::from_utf8_lossy(&o.stdout)
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for base in [env_path("ProgramFiles"), env_path("ProgramFiles(x86)")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
/// Where the tools live on this system.
|
||||
fn places() -> Vec<Option<PathBuf>> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let vs = base.join("Microsoft Visual Studio");
|
||||
for year in std::fs::read_dir(&vs).into_iter().flatten().flatten() {
|
||||
for edition in std::fs::read_dir(year.path())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
roots.push(edition.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
// The C++ tools are there if a version of them has its 64-bit linker.
|
||||
roots.iter().any(|root| {
|
||||
std::fs::read_dir(root.join("VC").join("Tools").join("MSVC"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.any(|v| {
|
||||
v.path()
|
||||
.join("bin")
|
||||
.join("Hostx64")
|
||||
.join("x64")
|
||||
.join("link.exe")
|
||||
.is_file()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Looks for the tools now.
|
||||
pub fn detect() -> Tools {
|
||||
let pf = env_path("ProgramFiles");
|
||||
let pf86 = env_path("ProgramFiles(x86)");
|
||||
let local = env_path("LOCALAPPDATA");
|
||||
let home = env_path("USERPROFILE");
|
||||
let git = find(
|
||||
"git",
|
||||
&[
|
||||
let pf = env_path("ProgramFiles");
|
||||
let pf86 = env_path("ProgramFiles(x86)");
|
||||
let local = env_path("LOCALAPPDATA");
|
||||
let home = env_path("USERPROFILE");
|
||||
vec![
|
||||
pf.as_ref()
|
||||
.map(|p| p.join("Git").join("cmd").join("git.exe")),
|
||||
pf86.as_ref()
|
||||
@@ -140,20 +105,40 @@ pub fn detect() -> Tools {
|
||||
local
|
||||
.as_ref()
|
||||
.map(|p| p.join("Programs").join("Git").join("cmd").join("git.exe")),
|
||||
],
|
||||
);
|
||||
let cargo = find(
|
||||
"cargo",
|
||||
&[
|
||||
env_path("CARGO_HOME").map(|p| p.join("bin").join("cargo.exe")),
|
||||
home.as_ref()
|
||||
.map(|p| p.join(".cargo").join("bin").join("cargo.exe")),
|
||||
],
|
||||
);
|
||||
]
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let home = env_path("HOME");
|
||||
vec![
|
||||
Some(PathBuf::from("/opt/homebrew/bin/git")),
|
||||
Some(PathBuf::from("/usr/local/bin/git")),
|
||||
Some(PathBuf::from("/usr/bin/git")),
|
||||
Some(PathBuf::from("/opt/homebrew/bin/cargo")),
|
||||
home.as_ref()
|
||||
.map(|p| p.join(".cargo").join("bin").join("cargo")),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the C++ build tools (Windows) or the Command Line Tools (macOS)
|
||||
/// are installed.
|
||||
fn build_tools_installed() -> bool {
|
||||
platform::build_tools_installed()
|
||||
}
|
||||
|
||||
/// Looks for the tools now.
|
||||
pub fn detect() -> Tools {
|
||||
let all = places();
|
||||
let git = find("git", &all[..all.len().saturating_sub(2)]);
|
||||
let cargo = find("cargo", &all[all.len().saturating_sub(2)..]);
|
||||
let t = Tools {
|
||||
git,
|
||||
cargo,
|
||||
msvc: msvc_installed(),
|
||||
clt: build_tools_installed(),
|
||||
};
|
||||
*FOUND.lock().unwrap() = Some(t.clone());
|
||||
t
|
||||
@@ -172,13 +157,19 @@ fn command(path: Option<PathBuf>, name: &str) -> Command {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !dirs.is_empty() {
|
||||
// The found tools first, then whatever the system had, then the standard
|
||||
// tool folders (macOS needs the last: a GUI app inherits a short `PATH`).
|
||||
let mut value = if dirs.is_empty() {
|
||||
std::env::var_os("PATH")
|
||||
} else {
|
||||
if let Some(path) = std::env::var_os("PATH") {
|
||||
dirs.extend(std::env::split_paths(&path));
|
||||
}
|
||||
if let Ok(joined) = std::env::join_paths(dirs) {
|
||||
c.env("PATH", joined);
|
||||
}
|
||||
std::env::join_paths(dirs).ok()
|
||||
};
|
||||
value = platform::with_tool_dirs(value);
|
||||
if let Some(value) = value {
|
||||
c.env("PATH", value);
|
||||
}
|
||||
c
|
||||
}
|
||||
@@ -191,39 +182,139 @@ pub fn cargo() -> Command {
|
||||
command(current().and_then(|t| t.cargo), "cargo")
|
||||
}
|
||||
|
||||
/// Whether winget (the Windows package manager) is there.
|
||||
pub fn has_winget() -> bool {
|
||||
answers(Path::new("winget"))
|
||||
/// Whether the system's package manager is there (winget; always on macOS,
|
||||
/// whose own tools do the job).
|
||||
pub fn has_manager() -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
answers(Path::new("winget"))
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The winget installs for what `t` lacks: (what, arguments).
|
||||
pub fn install_steps(t: &Tools) -> Vec<(&'static str, Vec<String>)> {
|
||||
let common = [
|
||||
"--exact",
|
||||
"--source",
|
||||
"winget",
|
||||
"--accept-package-agreements",
|
||||
"--accept-source-agreements",
|
||||
];
|
||||
let mut steps = Vec::new();
|
||||
let mut step = |what: &'static str, id: &str, extra: &[&str]| {
|
||||
let mut a: Vec<String> = vec!["install".into(), "--id".into(), id.into()];
|
||||
a.extend(common.iter().map(|s| s.to_string()));
|
||||
a.extend(extra.iter().map(|s| s.to_string()));
|
||||
steps.push((what, a));
|
||||
};
|
||||
if t.git.is_none() {
|
||||
step("Git", "Git.Git", &["--silent"]);
|
||||
/// One install step: what it is for, the program, and its arguments.
|
||||
pub struct Step {
|
||||
pub what: &'static str,
|
||||
pub program: &'static str,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
/// The installs for what `t` lacks, run in this order.
|
||||
pub fn install_steps(t: &Tools) -> Vec<Step> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let common = [
|
||||
"--exact",
|
||||
"--source",
|
||||
"winget",
|
||||
"--accept-package-agreements",
|
||||
"--accept-source-agreements",
|
||||
];
|
||||
let mut steps = Vec::new();
|
||||
let mut step = |what: &'static str, id: &str, extra: &[&str]| {
|
||||
let mut args: Vec<String> = vec!["install".into(), "--id".into(), id.into()];
|
||||
args.extend(common.iter().map(|s| s.to_string()));
|
||||
args.extend(extra.iter().map(|s| s.to_string()));
|
||||
steps.push(Step {
|
||||
what,
|
||||
program: "winget",
|
||||
args,
|
||||
});
|
||||
};
|
||||
if t.git.is_none() {
|
||||
step("Git", "Git.Git", &["--silent"]);
|
||||
}
|
||||
if !t.clt {
|
||||
step(
|
||||
BUILD_TOOLS,
|
||||
"Microsoft.VisualStudio.2022.BuildTools",
|
||||
&["--override", "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"],
|
||||
);
|
||||
}
|
||||
if t.cargo.is_none() {
|
||||
step("Rust", "Rustlang.Rustup", &["--silent"]);
|
||||
}
|
||||
steps
|
||||
}
|
||||
if !t.msvc {
|
||||
step(
|
||||
"C++ build tools",
|
||||
"Microsoft.VisualStudio.2022.BuildTools",
|
||||
&["--override", "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"],
|
||||
);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let mut steps = Vec::new();
|
||||
if !t.clt {
|
||||
// Apple's installer window opens; the caller waits for the tools to answer.
|
||||
steps.push(Step {
|
||||
what: BUILD_TOOLS,
|
||||
program: "/usr/bin/xcode-select",
|
||||
args: vec!["--install".into()],
|
||||
});
|
||||
}
|
||||
if t.git.is_none() && answers(Path::new("/opt/homebrew/bin/brew")) {
|
||||
steps.push(Step {
|
||||
what: "Git",
|
||||
program: "/opt/homebrew/bin/brew",
|
||||
args: vec!["install".into(), "git".into()],
|
||||
});
|
||||
}
|
||||
if t.cargo.is_none() {
|
||||
// The official installer, downloaded first so it is visible in the log.
|
||||
let script = std::env::temp_dir().join("vilauncher-rustup-init.sh");
|
||||
steps.push(Step {
|
||||
what: "Rust",
|
||||
program: "/usr/bin/curl",
|
||||
args: vec![
|
||||
"--proto".into(),
|
||||
"=https".into(),
|
||||
"--tlsv1.2".into(),
|
||||
"-sSfL".into(),
|
||||
"https://sh.rustup.rs".into(),
|
||||
"-o".into(),
|
||||
script.display().to_string(),
|
||||
],
|
||||
});
|
||||
steps.push(Step {
|
||||
what: "Rust",
|
||||
program: "/bin/sh",
|
||||
args: vec![script.display().to_string(), "-y".into()],
|
||||
});
|
||||
}
|
||||
steps
|
||||
}
|
||||
if t.cargo.is_none() {
|
||||
step("Rust", "Rustlang.Rustup", &["--silent"]);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
let _ = t;
|
||||
Vec::new()
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// Waits (up to `seconds`) for a just-started install to answer.
|
||||
pub fn wait_until_installed(what: &str, seconds: u64) -> bool {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(seconds);
|
||||
loop {
|
||||
let now = detect();
|
||||
let done = match what {
|
||||
"Rust" => now.cargo.is_some(),
|
||||
"Git" => now.git.is_some(),
|
||||
_ => now.clt,
|
||||
};
|
||||
if done {
|
||||
return true;
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
/// The version of the found git, for the log.
|
||||
pub fn git_version() -> Option<String> {
|
||||
let t = current()?;
|
||||
let mut c = command(t.git, "git");
|
||||
c.arg("--version");
|
||||
let out = c.output().ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
|
||||
}
|
||||
+226
-7
@@ -1,7 +1,11 @@
|
||||
use crate::notify::Ctx;
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::io::Read;
|
||||
#[cfg(windows)]
|
||||
use std::io::Write;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::Duration;
|
||||
@@ -9,7 +13,12 @@ use std::time::Duration;
|
||||
use crate::brand::{RELEASE_ASSET as ASSET, REPOSITORY};
|
||||
|
||||
pub const RELEASES: &str = "https://github.com/dazacode/vilauncher/releases";
|
||||
/// The largest download accepted: the portable exe on Windows, the app
|
||||
/// bundle's tarball on macOS.
|
||||
#[cfg(windows)]
|
||||
const MAX_BYTES: u64 = 64 * 1024 * 1024;
|
||||
#[cfg(not(windows))]
|
||||
const MAX_BYTES: u64 = 400 * 1024 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Release {
|
||||
@@ -139,19 +148,24 @@ fn check_release() -> Result<State, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn download_release(release: &Release) -> Result<DownloadedUpdate, String> {
|
||||
let asset = release
|
||||
/// The asset for this system in a release, or a message saying there is none.
|
||||
fn pick_asset<'a>(release: &'a Release, asset_name: &str) -> Result<&'a Asset, String> {
|
||||
release
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.name == ASSET)
|
||||
.ok_or_else(|| format!("This release has no {ASSET} download."))?;
|
||||
.find(|asset| asset.name == asset_name)
|
||||
.ok_or_else(|| format!("This release has no {asset_name} download."))
|
||||
}
|
||||
|
||||
fn download_release(release: &Release) -> Result<DownloadedUpdate, String> {
|
||||
let asset = pick_asset(release, ASSET)?;
|
||||
let digest = asset
|
||||
.digest
|
||||
.as_deref()
|
||||
.and_then(|digest| digest.strip_prefix("sha256:"))
|
||||
.ok_or("GitHub did not provide a SHA-256 checksum for the executable.")?;
|
||||
.ok_or("GitHub did not provide a SHA-256 checksum for the download.")?;
|
||||
if asset.size == 0 || asset.size > MAX_BYTES {
|
||||
return Err("The executable size is outside the supported limit.".into());
|
||||
return Err("The download size is outside the supported limit.".into());
|
||||
}
|
||||
let url = format!("{RELEASES}/download/{}/{ASSET}", release.tag_name);
|
||||
let response = agent()
|
||||
@@ -185,6 +199,9 @@ fn download_release(release: &Release) -> Result<DownloadedUpdate, String> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces the running launcher and starts the new one. Windows: the
|
||||
/// portable exe beside it. macOS: the whole `.app` bundle.
|
||||
#[cfg(windows)]
|
||||
pub fn restart_with(update: &DownloadedUpdate) -> Result<(), String> {
|
||||
let executable = std::env::current_exe().map_err(|error| error.to_string())?;
|
||||
let staged = executable.with_extension(format!("vilauncher-{}.tmp", std::process::id()));
|
||||
@@ -242,6 +259,183 @@ pub fn restart_with(update: &DownloadedUpdate) -> Result<(), String> {
|
||||
result
|
||||
}
|
||||
|
||||
/// Copies an `.app` bundle (or a folder) with `ditto`: it keeps symlinks,
|
||||
/// permission bits, extended attributes and the code signature intact, which
|
||||
/// `fs::copy` per file does not.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn copy_bundle(from: &PathBuf, to: &Path) -> Result<(), String> {
|
||||
let status = std::process::Command::new("/usr/bin/ditto")
|
||||
.arg(from)
|
||||
.arg(to)
|
||||
.status()
|
||||
.map_err(|error| format!("ditto did not run: {error}"))?;
|
||||
status
|
||||
.success()
|
||||
.then_some(())
|
||||
.ok_or_else(|| "ditto could not copy the new app bundle".to_string())
|
||||
}
|
||||
|
||||
/// Drops Gatekeeper's quarantine flag so the replaced app starts without a
|
||||
/// prompt. Best effort: a copy made by `ditto` from a local file may carry none.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn clear_quarantine(path: &Path) {
|
||||
let _ = std::process::Command::new("/usr/bin/xattr")
|
||||
.args(["-dr", "com.apple.quarantine"])
|
||||
.arg(path)
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Replaces the running `.app` bundle with the downloaded one and starts it.
|
||||
///
|
||||
/// The archive's SHA-256 is checked again, it is unpacked into a staging
|
||||
/// folder on the same volume, its program is checked, and only then is the
|
||||
/// old bundle moved aside. Any failure puts the old bundle back; a bundle on
|
||||
/// a read-only volume (a mounted DMG, `/Applications` for another user) is
|
||||
/// replaced through `osascript` with an administrator prompt instead.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn restart_with(update: &DownloadedUpdate) -> Result<(), String> {
|
||||
fn quoted(path: &std::path::Path) -> String {
|
||||
format!("'{}'", path.display().to_string().replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
let exe = std::env::current_exe().map_err(|error| error.to_string())?;
|
||||
let bundle = exe
|
||||
.ancestors()
|
||||
.find(|part| part.extension().is_some_and(|ext| ext == "app"))
|
||||
.ok_or("The launcher is not running from an .app bundle, so it cannot replace itself.")?
|
||||
.to_path_buf();
|
||||
let parent = bundle
|
||||
.parent()
|
||||
.ok_or("The app bundle has no folder.")?
|
||||
.to_path_buf();
|
||||
let name = bundle
|
||||
.file_name()
|
||||
.ok_or("The app bundle has no name.")?
|
||||
.to_owned();
|
||||
let backup = parent.join(format!(
|
||||
".{}.previous",
|
||||
name.to_string_lossy().trim_end_matches(".app")
|
||||
));
|
||||
let source = fs::File::open(&update.path).map_err(|error| error.to_string())?;
|
||||
let mut bytes = Vec::new();
|
||||
source
|
||||
.take(update.size + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if !matches_asset(&bytes, update.size, &update.digest) {
|
||||
return Err(
|
||||
"The downloaded update changed on disk. Check for updates and download it again."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
// A fresh staging folder next to the bundle, so the last steps are renames.
|
||||
let staging = update
|
||||
.path
|
||||
.with_file_name(format!("staged-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
fs::create_dir_all(&staging).map_err(|error| error.to_string())?;
|
||||
let unpack = std::process::Command::new("/usr/bin/tar")
|
||||
.arg("-xzf")
|
||||
.arg(&update.path)
|
||||
.arg("-C")
|
||||
.arg(&staging)
|
||||
.status()
|
||||
.map_err(|error| format!("Could not unpack the update: {error}"))?;
|
||||
if !unpack.success() {
|
||||
return Err("The downloaded update could not be unpacked.".into());
|
||||
}
|
||||
let staged_app = fs::read_dir(&staging)
|
||||
.map_err(|error| error.to_string())?
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.find(|path| path.extension().is_some_and(|ext| ext == "app") && path.is_dir())
|
||||
.ok_or("The update archive holds no .app bundle.")?;
|
||||
let program = staged_app.join("Contents").join("MacOS");
|
||||
let ok = fs::read_dir(&program)
|
||||
.ok()
|
||||
.map(|mut entries| entries.any(|e| e.is_ok_and(|e| e.path().is_file())))
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
return Err("The update's app bundle holds no program.".into());
|
||||
}
|
||||
|
||||
// Into place beside the bundle, then swap with renames.
|
||||
let target = parent.join(&name);
|
||||
if let Err(error) = copy_bundle(&staged_app, &target) {
|
||||
let _ = fs::remove_dir_all(&target);
|
||||
return Err(format!("Could not put the update in place: {error}"));
|
||||
}
|
||||
clear_quarantine(&target);
|
||||
let swap = |target: &PathBuf| -> Result<(), String> {
|
||||
let _ = fs::remove_dir_all(&backup);
|
||||
fs::rename(&bundle, &backup)
|
||||
.map_err(|error| format!("Could not move the running launcher aside: {error}"))?;
|
||||
if let Err(error) = fs::rename(target, &bundle) {
|
||||
let _ = fs::rename(&backup, &bundle);
|
||||
return Err(format!("Could not put the update in place: {error}"));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match swap(&target) {
|
||||
Ok(()) => {}
|
||||
Err(_error) if parent_is_read_only(&parent) => {
|
||||
// A mounted DMG or a bundle owned by another user: ask for an administrator.
|
||||
let script = format!(
|
||||
"rm -rf {} && mv {} {} && rm -rf {}",
|
||||
quoted(&bundle),
|
||||
quoted(&target),
|
||||
quoted(&bundle),
|
||||
quoted(&backup)
|
||||
);
|
||||
let script = script.replace('\\', "\\\\").replace('"', "\\\"");
|
||||
let status = std::process::Command::new("/usr/bin/osascript")
|
||||
.args([
|
||||
"-e",
|
||||
&format!("do shell script \"{script}\" with administrator privileges"),
|
||||
])
|
||||
.status()
|
||||
.map_err(|error| {
|
||||
format!("{error} (the update is ready in {})", target.display())
|
||||
})?;
|
||||
if !status.success() {
|
||||
return Err(format!(
|
||||
"macOS did not allow replacing the app. Move it to a folder you own, or install the update from {} yourself.",
|
||||
target.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = fs::remove_dir_all(&target);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let started = std::process::Command::new("/usr/bin/open")
|
||||
.args(["-n"])
|
||||
.arg(&bundle)
|
||||
.spawn();
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
match started {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) => Err(format!(
|
||||
"The update is in place but could not be started: {error}. Open VILauncher from Applications."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the folder refuses a new entry (a mounted DMG, another user's
|
||||
/// folder). Probed, because permission bits alone mislead on ACLs.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn parent_is_read_only(parent: &std::path::Path) -> bool {
|
||||
let probe = parent.join(format!(".vilauncher-write-{}", std::process::id()));
|
||||
match fs::write(&probe, b"probe") {
|
||||
Ok(()) => {
|
||||
let _ = fs::remove_file(&probe);
|
||||
false
|
||||
}
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches_asset(bytes: &[u8], size: u64, sha256: &str) -> bool {
|
||||
let actual = ring::digest::digest(&ring::digest::SHA256, bytes);
|
||||
let actual: String = actual
|
||||
@@ -271,6 +465,31 @@ fn compares_stable_versions_numerically() {
|
||||
assert!(version("v0.3.0/other").is_none());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn the_system_s_asset_is_picked_from_a_release() {
|
||||
let release = Release {
|
||||
tag_name: "v1.2.3".into(),
|
||||
assets: vec![
|
||||
Asset {
|
||||
name: "VILauncher.exe".into(),
|
||||
size: 1,
|
||||
digest: None,
|
||||
},
|
||||
Asset {
|
||||
name: "VILauncher-macos.app.tar.gz".into(),
|
||||
size: 2,
|
||||
digest: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
pick_asset(&release, ASSET).unwrap().size,
|
||||
if cfg!(windows) { 1 } else { 2 }
|
||||
);
|
||||
assert!(pick_asset(&release, "VILauncher-linux").is_err());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn rejects_changed_or_truncated_downloads() {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "VILauncher",
|
||||
"width": 1360,
|
||||
"height": 860,
|
||||
"minWidth": 1024,
|
||||
"minHeight": 680,
|
||||
"decorations": true,
|
||||
"titleBarStyle": "Overlay",
|
||||
"hiddenTitle": true,
|
||||
"transparent": true,
|
||||
"center": true,
|
||||
"backgroundColor": "#0c0b10"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bundle": {
|
||||
"targets": ["app", "dmg"],
|
||||
"category": "public.app-category.games",
|
||||
"macOS": {
|
||||
"minimumSystemVersion": "13.0",
|
||||
"hardenedRuntime": true,
|
||||
"signingIdentity": "-",
|
||||
"entitlements": "Entitlements.plist"
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -8,11 +8,12 @@ import { Dialogs } from "@/features/dialogs/dialogs"
|
||||
import { LibrarySkeleton, LibraryView } from "@/features/library/library-view"
|
||||
import { WorkshopView } from "@/features/library/workshop-view"
|
||||
import { SettingsView } from "@/features/settings/settings-view"
|
||||
import { getBackend } from "@/lib/api"
|
||||
import { getBackend, platformName } from "@/lib/api"
|
||||
import { scheduleRefresh, useStore } from "@/lib/store"
|
||||
|
||||
export function App() {
|
||||
const snap = useStore((s) => s.snap)
|
||||
const mac = (snap?.brand.platform ?? platformName()) === "macos"
|
||||
const view = useStore((s) => s.view)
|
||||
useEffect(() => {
|
||||
let off: (() => void) | undefined
|
||||
@@ -28,8 +29,9 @@ export function App() {
|
||||
<Sidebar />
|
||||
<main className="relative min-w-0 flex-1 overflow-hidden bg-[#0b0910]">
|
||||
{/* The top of the window drags it; the controls and the page nav sit over the art. */}
|
||||
{/* macOS draws its own traffic lights (top left, over the sidebar), so no buttons here. */}
|
||||
<div className="drag absolute inset-x-0 top-0 z-40 flex h-[28px] justify-end">
|
||||
<WindowControls />
|
||||
{!mac && <WindowControls />}
|
||||
</div>
|
||||
<div className="drag absolute inset-x-0 top-[28px] z-30 flex h-[52px] items-center justify-end pr-[53px]">
|
||||
<TopNav />
|
||||
|
||||
+25
-5
@@ -1,6 +1,7 @@
|
||||
// A stand-in launcher for working on the UI in a plain browser (pnpm dev).
|
||||
// Never part of the app: api.ts loads it only outside the Tauri window.
|
||||
// ?state=fresh (nothing set up) · ready (set up, one installed) · job (a build running).
|
||||
// ?platform=macos (or windows) previews the other system's labels and chrome.
|
||||
|
||||
import type { Action, Graphics, LogView, Project, ResponsibilityId, Snapshot, StorageView } from "@/lib/types"
|
||||
|
||||
@@ -11,6 +12,7 @@ const mode = params.get("state") ?? "ready"
|
||||
const listeners = new Set<() => void>()
|
||||
const changed = () => listeners.forEach((l) => l())
|
||||
|
||||
const platform = (params.get("platform") ?? (navigator.userAgent.includes("Mac") ? "macos" : "windows")) as "macos" | "windows"
|
||||
const graphics: Graphics = { series_s: true, render_scale: 0.5, fix_8gb: true, bright_shadows: true, fullscreen: false, output: "Default" }
|
||||
const state = {
|
||||
selected: (params.get("select") ?? SAMPLE[1]?.repo ?? null) as string | null,
|
||||
@@ -51,7 +53,8 @@ function project(s: (typeof SAMPLE)[number], index: number): Project {
|
||||
reported: index === 1 ? { ram_gb: 30, vram_gb: 12 } : { ram_gb: null, vram_gb: null },
|
||||
owner: s.repo.split("/")[0],
|
||||
custom: false,
|
||||
kind: "git",
|
||||
kind: index === 3 ? "zip" : "git",
|
||||
binary: index === 3 ? (platform === "macos" ? "windows" : "native") : "native",
|
||||
web_url: `https://github.com/${s.repo}`,
|
||||
installed,
|
||||
checking: false,
|
||||
@@ -74,11 +77,17 @@ function project(s: (typeof SAMPLE)[number], index: number): Project {
|
||||
}
|
||||
}
|
||||
|
||||
// The mocked PC follows the previewed platform, so both states look real.
|
||||
const system: Snapshot["system"] =
|
||||
platform === "macos"
|
||||
? { gpus: [{ name: "Apple M3 (Unified Memory)", vendor: "Apple", vram_gb: 12 }], ram_gb: 16, cpu: "Apple M3", cpu_cores: 8, translated: false }
|
||||
: { gpus: [{ name: "NVIDIA GeForce RTX 4060", vendor: "NVIDIA", vram_gb: 8 }], ram_gb: 16, cpu: "AMD Ryzen 7 5800X 8-Core Processor", cpu_cores: 16, translated: false }
|
||||
|
||||
function snapshot(): Snapshot {
|
||||
return {
|
||||
version: "0.1.0",
|
||||
notice_accepted: state.notice,
|
||||
brand: { name: "VILauncher", team: "VIPortLive team", site: "https://viportlive.com", site_label: "viportlive.com", source: "https://github.com/dazacode/vilauncher" },
|
||||
brand: { name: "VILauncher", team: "VIPortLive team", site: "https://viportlive.com", site_label: "viportlive.com", source: "https://github.com/dazacode/vilauncher", platform },
|
||||
list: { status: "ready", error: null, items: SAMPLE.map(project) },
|
||||
custom: [],
|
||||
selected: state.selected,
|
||||
@@ -97,13 +106,24 @@ function snapshot(): Snapshot {
|
||||
list_tier: state.listTier ?? 0,
|
||||
spec_ram_gb: state.specRam ?? null,
|
||||
spec_vram_gb: state.specVram ?? null,
|
||||
backgrounds_dir: "C:\\Users\\you\\AppData\\Local\\VILauncher\\backgrounds",
|
||||
backgrounds_dir:
|
||||
platform === "macos"
|
||||
? "/Users/you/Library/Application Support/VILauncher/backgrounds"
|
||||
: "C:\\Users\\you\\AppData\\Local\\VILauncher\\backgrounds",
|
||||
skip_update_warning: state.skipUpdateWarning,
|
||||
agent_access: state.agentAccess,
|
||||
acknowledged: state.acknowledged,
|
||||
},
|
||||
files: { chosen: !!state.gameDir, ok: !!state.gameDir, empty: false, unplugged: false, missing: state.gameDir ? [] : [], searching: false, find_error: null },
|
||||
tools: { ready: state.toolsReady, missing: state.toolsReady ? [] : ["C++ build tools"] },
|
||||
tools: {
|
||||
ready: state.toolsReady,
|
||||
missing: state.toolsReady ? [] : [platform === "macos" ? "Xcode Command Line Tools" : "C++ build tools"],
|
||||
build_tools: platform === "macos" ? "Xcode Command Line Tools" : "C++ build tools",
|
||||
install_hint:
|
||||
platform === "macos"
|
||||
? "Uses Apple's Command Line Tools installer and rustup; macOS asks for permission."
|
||||
: "Installs with winget; Windows asks for permission.",
|
||||
},
|
||||
job: {
|
||||
running: !!state.job,
|
||||
repo: state.job?.repo ?? null,
|
||||
@@ -117,7 +137,7 @@ function snapshot(): Snapshot {
|
||||
pending_move: null,
|
||||
presets: [],
|
||||
backgrounds: [],
|
||||
system: { gpus: [{ name: "NVIDIA GeForce RTX 4060", vendor: "NVIDIA", vram_gb: 8 }], ram_gb: 16, cpu: "AMD Ryzen 7 5800X 8-Core Processor", cpu_cores: 16 },
|
||||
system,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -1,5 +1,17 @@
|
||||
import type { Action, LogView, Snapshot } from "./types"
|
||||
|
||||
/**
|
||||
* The system this runs on, from the browser or webview's own description. The
|
||||
* snapshot's `brand.platform` is the launcher's answer; this covers the first
|
||||
* paint and the browser mock.
|
||||
*/
|
||||
export function platformName(): "windows" | "macos" | "other" {
|
||||
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent
|
||||
if (/Macintosh|Mac OS X/i.test(ua)) return "macos"
|
||||
if (/Windows/i.test(ua)) return "windows"
|
||||
return "other"
|
||||
}
|
||||
|
||||
/** True inside the Tauri window; false in a plain browser (development, with a mock launcher). */
|
||||
export const inTauri = typeof window !== "undefined" && "__TAURI_INTERNALS__" in window
|
||||
|
||||
@@ -96,7 +108,8 @@ export async function copyText(text: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a web link: the opener plugin, then the launcher itself (Explorer opens the default browser).
|
||||
* Opens a web link: the opener plugin, then the launcher itself (the system's
|
||||
* shell opens the default browser).
|
||||
* Throws only when both fail, so the caller can say so.
|
||||
*/
|
||||
export async function openUrl(url: string) {
|
||||
|
||||
+6
-2
@@ -32,6 +32,8 @@ export interface SystemInfo {
|
||||
ram_gb: number | null
|
||||
cpu: string | null
|
||||
cpu_cores: number | null
|
||||
/** Running under Rosetta 2 (a translated process on Apple silicon). */
|
||||
translated?: boolean
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
@@ -59,6 +61,8 @@ export interface Project {
|
||||
reported: { ram_gb: number | null; vram_gb: number | null }
|
||||
custom: boolean
|
||||
kind: "git" | "zip" | "local"
|
||||
/** The program's format, when there is one: a Windows program needs a runner on a Mac. */
|
||||
binary: "windows" | "native" | "script" | "unknown" | null
|
||||
web_url: string | null
|
||||
installed: boolean
|
||||
checking: boolean
|
||||
@@ -89,7 +93,7 @@ export interface Project {
|
||||
export interface Snapshot {
|
||||
version: string
|
||||
notice_accepted: boolean
|
||||
brand: { name: string; team: string; site: string; site_label: string; source: string }
|
||||
brand: { name: string; team: string; site: string; site_label: string; source: string; platform: "windows" | "macos" | string }
|
||||
list: { status: "loading" | "error" | "ready"; error: string | null; items: Project[] }
|
||||
custom: Project[]
|
||||
selected: string | null
|
||||
@@ -126,7 +130,7 @@ export interface Snapshot {
|
||||
searching: boolean
|
||||
find_error: string | null
|
||||
}
|
||||
tools: { ready: boolean; missing: string[] } | null
|
||||
tools: { ready: boolean; missing: string[]; build_tools: string; install_hint: string } | null
|
||||
job: {
|
||||
running: boolean
|
||||
repo: string | null
|
||||
|
||||
+7
-3
@@ -1,11 +1,15 @@
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { App } from "./App"
|
||||
import { inTauri } from "./lib/api"
|
||||
import { inTauri, platformName } from "./lib/api"
|
||||
import "./styles.css"
|
||||
|
||||
// Inside the window the system's glass (Mica) shows through; elsewhere, a solid ground.
|
||||
if (inTauri && navigator.userAgent.includes("Windows")) document.body.classList.add("has-glass")
|
||||
// Inside the window the system's glass (Mica on Windows, the sidebar material
|
||||
// on macOS) shows through; elsewhere, a solid ground. The platform class drives
|
||||
// window chrome: macOS keeps the traffic lights, Windows draws its own.
|
||||
const platform = platformName()
|
||||
if (inTauri && platform !== "other") document.body.classList.add("has-glass")
|
||||
document.body.classList.add(platform === "macos" ? "is-mac" : "is-windows")
|
||||
document.addEventListener("contextmenu", (e) => {
|
||||
if (!(e.target as HTMLElement).closest("input, textarea, [data-selectable]")) e.preventDefault()
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user