mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
packaging(linux): support co-installable nightly packages (#801)
Linux nightly packaging by @dylanmtaylor, with the per-app Nightly flavor commits stacked on his branch. Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
1 parent
2a4ad138d9
commit
56efb48efb
72 files changed
+5488
-80
No files matched your search
@@ -1,2 +1,71 @@
|
||||
// The same build provenance and Windows icon/VERSIONINFO as the app; see that file.
|
||||
include!("../texturecraft/build.rs");
|
||||
// Provenance for the headless CLI: the same commit and date variables as the app, and (Windows
|
||||
// only) its own icon and VERSIONINFO into `texturecraft-cli.exe`.
|
||||
//
|
||||
// This is deliberately not an `include!` of the app's build script: that one resolves a `#[path]`
|
||||
// submodule and reads the Nightly channel, neither of which a CLI build has any use for, and a
|
||||
// module path inside an included script is resolved from the included file, not from here.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
const ICON: &str = "../../assets/app-icon/texturecraft.ico";
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-changed={ICON}");
|
||||
for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] {
|
||||
println!("cargo:rerun-if-env-changed={var}");
|
||||
}
|
||||
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha));
|
||||
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today));
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
windows_resources();
|
||||
}
|
||||
}
|
||||
|
||||
fn env_or(var: &str, fallback: fn() -> Option<String>) -> String {
|
||||
std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn git_sha() -> Option<String> {
|
||||
let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?;
|
||||
let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned();
|
||||
(sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha)
|
||||
}
|
||||
|
||||
/// UTC date of `SOURCE_DATE_EPOCH`, or of now.
|
||||
fn today() -> Option<String> {
|
||||
let secs = match std::env::var("SOURCE_DATE_EPOCH") {
|
||||
Ok(v) => v.trim().parse::<u64>().ok()?,
|
||||
Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(),
|
||||
};
|
||||
// Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian).
|
||||
let z = i64::try_from(secs / 86_400).ok()? + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
Some(format!("{year:04}-{month:02}-{day:02}"))
|
||||
}
|
||||
|
||||
fn windows_resources() {
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon(ICON)
|
||||
.set("ProductName", "TextureCraft")
|
||||
.set("FileDescription", "TextureCraft command-line tool")
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "texturecraft-cli.exe")
|
||||
.set("InternalName", "texturecraft-cli");
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() {
|
||||
println!("cargo::error=embedding Windows resources into texturecraft-cli.exe failed: {e}");
|
||||
} else {
|
||||
println!("cargo:warning=texturecraft-cli.exe built without icon/version resources: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,8 +120,18 @@ fn version() -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// The desktop app's Nightly launch options. The CLI never takes them: a Nightly install ships the
|
||||
/// GUI only, and a script that passes them to the CLI has the wrong program.
|
||||
fn is_launch_profile_flag(arg: &str) -> bool {
|
||||
arg == "--launch-profile" || arg == "--profile-root" || arg.starts_with("--launch-profile=") || arg.starts_with("--profile-root=")
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if let Some(flag) = args.iter().find(|arg| is_launch_profile_flag(arg.as_str())) {
|
||||
eprintln!("texturecraft-cli: `{flag}` is a TextureCraft desktop launch option, not a CLI argument");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let code = match args.first().map(String::as_str) {
|
||||
None => {
|
||||
eprint!("{USAGE}");
|
||||
|
||||
@@ -30,7 +30,8 @@ ron = "0.12"
|
||||
# borderless (src/window_frame.rs; winsafe is MIT, User32 only).
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winit = { version = "0.30", default-features = false }
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"] }
|
||||
# `shell` carries SetCurrentProcessExplicitAppUserModelID, the Nightly taskbar identity (src/process_identity.rs).
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user", "shell"] }
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
|
||||
+67
-10
@@ -2,31 +2,78 @@
|
||||
//
|
||||
// Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file).
|
||||
//
|
||||
// - Sets `TEXTURECRAFT_VERSION` for `env!`: the prepared Nightly feed identity when
|
||||
// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1`, else the workspace package version. A Nightly build
|
||||
// without a well-formed `TEXTURECRAFT_VERSION` fails rather than falling back to the Cargo
|
||||
// version, so an archive can never carry the wrong identity.
|
||||
// - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE`
|
||||
// (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and
|
||||
// packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for
|
||||
// reproducible builds); either is an empty string when unknown, so source tarballs, wasm and
|
||||
// offline builds still compile. Without the env vars the commit is read when this script runs,
|
||||
// so a local build can show a stale commit; release builds always set the variable.
|
||||
// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe.
|
||||
// - Windows targets only: embeds the flavor's `assets/app-icon/*.ico` and VERSIONINFO into the exe.
|
||||
// A missing resource compiler is a warning, so a cross-compile still links, unless
|
||||
// `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error.
|
||||
|
||||
use std::process::Command;
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
const ICON: &str = "../../assets/app-icon/texturecraft.ico";
|
||||
use std::process::Command;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-changed={ICON}");
|
||||
for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] {
|
||||
println!("cargo:rerun-if-changed=src/build_channel.rs");
|
||||
for icon in [build_channel::windows_icon_path(false), build_channel::windows_icon_path(true)] {
|
||||
println!("cargo:rerun-if-changed={icon}");
|
||||
}
|
||||
for var in [
|
||||
"TEXTURECRAFT_BUILD_SHA",
|
||||
"TEXTURECRAFT_BUILD_DATE",
|
||||
"TEXTURECRAFT_BUILD_CHANNEL",
|
||||
"TEXTURECRAFT_VERSION",
|
||||
"TEXTURECRAFT_OVERRIDE_VERSION",
|
||||
"TEXTURECRAFT_REQUIRE_WINRES",
|
||||
"SOURCE_DATE_EPOCH",
|
||||
] {
|
||||
println!("cargo:rerun-if-env-changed={var}");
|
||||
}
|
||||
println!("cargo:rustc-check-cfg=cfg(texturecraft_nightly_v1)");
|
||||
let nightly = match std::env::var("TEXTURECRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=texturecraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported TEXTURECRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
// `TEXTURECRAFT_VERSION` is the feed identity the workflow exports; the packaging scripts
|
||||
// (packaging/env.sh, nightly-common.sh, linux/package.sh) spell the same value
|
||||
// `TEXTURECRAFT_OVERRIDE_VERSION`, so both name the version the binary reports.
|
||||
let requested = ["TEXTURECRAFT_VERSION", "TEXTURECRAFT_OVERRIDE_VERSION"]
|
||||
.into_iter()
|
||||
.find_map(|name| std::env::var(name).ok().map(|value| value.trim().to_owned()).filter(|value| !value.is_empty()));
|
||||
let built_version = if nightly {
|
||||
match requested {
|
||||
Some(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit prepared feed identity in TEXTURECRAFT_VERSION");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=TEXTURECRAFT_VERSION={built_version}");
|
||||
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha));
|
||||
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today));
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
windows_resources();
|
||||
windows_resources(nightly, &built_version);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,17 +106,27 @@ fn today() -> Option<String> {
|
||||
Some(format!("{year:04}-{month:02}-{day:02}"))
|
||||
}
|
||||
|
||||
fn windows_resources() {
|
||||
fn windows_resources(nightly: bool, built_version: &str) {
|
||||
let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into());
|
||||
let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" };
|
||||
let description = if name.ends_with("-cli") {
|
||||
if nightly { "TextureCraft Nightly command-line tool" } else { "TextureCraft command-line tool" }
|
||||
} else if nightly {
|
||||
"TextureCraft Nightly 3D texture painter"
|
||||
} else {
|
||||
"TextureCraft 3D texture painter"
|
||||
};
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon(ICON)
|
||||
.set("ProductName", "TextureCraft")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "TextureCraft Nightly" } else { "TextureCraft" })
|
||||
.set("FileDescription", description)
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", &format!("{name}.exe"))
|
||||
.set("InternalName", &name);
|
||||
if nightly {
|
||||
// The Launcher checks the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() {
|
||||
println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}");
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
//!
|
||||
//! `build.rs` includes this file (`#[path = "src/build_channel.rs"]`) and the app compiles it for
|
||||
//! the same checks, so the icon and the version shape cannot drift apart between them.
|
||||
|
||||
/// `X.Y.Z-nightly.YYYYMMDD.<run>.<attempt>.g<sha12>`, the Launcher's immutable feed identity.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
|
||||
/// The Windows icon embedded in the executable: the nightly art only in a nightly build.
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/texturecraft-nightly.ico" } else { "../../assets/app-icon/texturecraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/texturecraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/texturecraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.23.1",
|
||||
"0.23.1-nightly",
|
||||
"0.23.1-nightly.20261120",
|
||||
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
|
||||
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
|
||||
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
|
||||
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! The build-time channel, which is distinct from a launch selector: no runtime environment can
|
||||
//! promote a stable build into the Nightly one.
|
||||
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`).
|
||||
pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
/// The version this binary was built as: the prepared feed identity in a nightly build, else the
|
||||
/// workspace version (`build.rs` bakes it so both flavors read it the same way).
|
||||
pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION");
|
||||
|
||||
/// A nightly build starts only with its profile, and a stable build only without one.
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A refused nightly start explains itself in a native dialog: a release Windows build has no
|
||||
/// console, and a Dock launch on macOS has none either.
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
/// `--version` or `-V` alone; a file called `--version` after `--` is never a query.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
/// The line `--version` prints: `<App> <version> (nightly-v1)` in a nightly build, exactly as the
|
||||
/// Launcher and the release smoke test read it.
|
||||
pub fn version(flavor: BuildFlavor) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => format!("TextureCraft {BUILT_VERSION}"),
|
||||
BuildFlavor::NightlyV1 => format!("TextureCraft {BUILT_VERSION} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nightly_version_line_is_exact_and_says_its_channel() {
|
||||
let nightly = version(BuildFlavor::NightlyV1);
|
||||
assert!(nightly.starts_with("TextureCraft "), "{nightly}");
|
||||
assert!(nightly.ends_with(" (nightly-v1)"), "{nightly}");
|
||||
assert_eq!(nightly, format!("TextureCraft {} (nightly-v1)", BUILT_VERSION));
|
||||
assert_eq!(version(BuildFlavor::Stable), format!("TextureCraft {BUILT_VERSION}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_bare_version_flag_is_a_query() {
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&["--version".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches keep their arguments and directory policy unchanged, and no environment is
|
||||
//! mutated: the profile is a value this process reads, not a variable it exports.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a
|
||||
/// file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old directory resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" }
|
||||
}
|
||||
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "model with spaces.glb"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]),
|
||||
] {
|
||||
assert!(parse(argv.clone()).is_err(), "{argv:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
+264
-19
@@ -5,11 +5,22 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod control_server;
|
||||
mod gpu;
|
||||
mod launch_profile;
|
||||
mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod window_frame;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use launch_profile::Profile;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::os_window::{self, LaunchIdentity};
|
||||
use texturecraft_ui_egui::titlebar::TitleBar;
|
||||
use texturecraft_ui_egui::ui_state_store;
|
||||
use texturecraft_ui_egui::{TextureCraftApp, UiState};
|
||||
@@ -17,14 +28,25 @@ use texturecraft_ui_egui::{TextureCraftApp, UiState};
|
||||
/// The app name eframe keeps the settings under (`eframe::storage_dir`).
|
||||
const APP_NAME: &str = "TextureCraft";
|
||||
|
||||
/// The data folder Dylan's #801 packaging lets a Stable wrapper set. A Nightly launch never reads
|
||||
/// it: its profile arrives as the Launcher's literal selector/root pair, and nothing else.
|
||||
const DATA_DIR_ENV: &str = "TEXTURECRAFT_DATA_DIR";
|
||||
|
||||
/// The window's size when it opens, in points.
|
||||
const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0];
|
||||
/// The smallest size the window can be resized to, in points.
|
||||
const MIN_SIZE: [f32; 2] = [960.0, 600.0];
|
||||
|
||||
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
|
||||
/// The Nightly window icon: the same artwork on the deeper background the package icon uses.
|
||||
const NIGHTLY_ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/texturecraft-nightly.png");
|
||||
|
||||
/// The version line: a Nightly build names its exact feed identity and channel, and every other
|
||||
/// build keeps the workspace version with the commit and date it was built from.
|
||||
fn version() -> String {
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 {
|
||||
return build_flavor::version(build_flavor::COMPILED);
|
||||
}
|
||||
let sha = env!("TEXTURECRAFT_BUILD_SHA");
|
||||
let short = sha.get(..7).unwrap_or(sha);
|
||||
let date = env!("TEXTURECRAFT_BUILD_DATE");
|
||||
@@ -44,15 +66,23 @@ struct Args {
|
||||
power_pref: Option<eframe::wgpu::PowerPreference>,
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Option<Args>, String> {
|
||||
parse_args_from(std::env::args().skip(1))
|
||||
}
|
||||
|
||||
fn parse_args_from<I: IntoIterator<Item = String>>(it: I) -> Result<Option<Args>, String> {
|
||||
let mut args = Args { file: None, control: None, empty: false, gpu: None, power_pref: None };
|
||||
let mut it = it.into_iter();
|
||||
// Everything after `--` is a file, even when it looks like an option: the Launcher's nightly
|
||||
// protocol passes the selected file that way (and a file may be called `--version`).
|
||||
let mut after_delimiter = false;
|
||||
while let Some(a) = it.next() {
|
||||
if after_delimiter {
|
||||
// A Launcher hand-off may carry more than one file. Opening the first one beats a
|
||||
// silent exit on a Windows build, which has no console to show the refusal on.
|
||||
if args.file.is_none() {
|
||||
args.file = Some(a);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match a.as_str() {
|
||||
"--" => after_delimiter = true,
|
||||
"--version" | "-V" => {
|
||||
println!("{}", version());
|
||||
return Ok(None);
|
||||
@@ -119,7 +149,8 @@ fn initial_session(args: &Args) -> Session {
|
||||
}
|
||||
|
||||
fn icon() -> Option<egui::IconData> {
|
||||
let img = craft_image_codecs::decode(ICON_PNG).ok()?;
|
||||
let png = if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 { NIGHTLY_ICON_PNG } else { ICON_PNG };
|
||||
let img = craft_image_codecs::decode(png).ok()?;
|
||||
Some(egui::IconData { rgba: img.to_rgba8(), width: img.width(), height: img.height() })
|
||||
}
|
||||
|
||||
@@ -134,13 +165,39 @@ fn set_taskbar_icon(w: &winit::window::Window) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Directory for saved settings, UI state, and error logs: a Nightly launch's validated profile,
|
||||
/// else `TEXTURECRAFT_DATA_DIR` (when non-empty, as a Stable package wrapper sets it), else
|
||||
/// eframe's own folder for this app.
|
||||
fn storage_dir() -> Option<std::path::PathBuf> {
|
||||
settings_folder(
|
||||
launch_profile::current().root(),
|
||||
std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(std::path::PathBuf::from),
|
||||
eframe::storage_dir(APP_NAME),
|
||||
)
|
||||
}
|
||||
|
||||
/// The settings folder, in the order a launch decides it: a Nightly profile, a Stable wrapper's
|
||||
/// `TEXTURECRAFT_DATA_DIR`, else eframe's own folder for this app.
|
||||
///
|
||||
/// The last one is passed in rather than left to eframe. With `with_app_id` set (the Linux window
|
||||
/// class the Stable entry needs), eframe derives its folder from the app id, so Stable's `app.ron`
|
||||
/// — window state and the user's export presets — would move to `ai.storyteller.texturecraft` while
|
||||
/// `ui.json` and `errors.log` stayed behind. `persistence_path` therefore names the file explicitly.
|
||||
fn settings_folder(
|
||||
profile: Option<&std::path::Path>,
|
||||
wrapper_dir: Option<std::path::PathBuf>,
|
||||
legacy: Option<std::path::PathBuf>,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
profile.map(std::path::Path::to_path_buf).or(wrapper_dir).or(legacy)
|
||||
}
|
||||
|
||||
/// Preferences needed before opening the initial project or window, with legacy storage fallback.
|
||||
fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs {
|
||||
if let Some(ui) = ui_file.and_then(ui_state_store::read) {
|
||||
return ui.prefs;
|
||||
}
|
||||
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron")));
|
||||
let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| storage_dir().map(|folder| folder.join("app.ron")));
|
||||
let saved = file.and_then(|file| std::fs::read_to_string(file).ok());
|
||||
let entries = saved.and_then(|text| ron::from_str::<std::collections::HashMap<String, String>>(&text).ok());
|
||||
entries.and_then(|entries| ron::from_str::<UiState>(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default()
|
||||
@@ -151,6 +208,10 @@ fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std:
|
||||
struct Shell {
|
||||
app: TextureCraftApp,
|
||||
window_frame: Option<window_frame::WindowFrameFn>,
|
||||
/// Runs once when the window closes. On macOS that is the only place a clean quit is handled:
|
||||
/// Cmd+Q ends the process inside AppKit's terminate, after eframe's `on_exit` and before
|
||||
/// `eframe::run_native` returns, so the Nightly session record is finished here, not there.
|
||||
exit_hook: Option<Box<dyn FnOnce()>>,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: Option<bool>,
|
||||
}
|
||||
@@ -183,6 +244,12 @@ impl eframe::App for Shell {
|
||||
#[cfg(target_os = "macos")]
|
||||
texturecraft_ui_egui::titlebar::sync_native(&self.app.title_bar, ui, frame, &mut self.movable);
|
||||
}
|
||||
|
||||
fn on_exit(&mut self) {
|
||||
if let Some(hook) = self.exit_hook.take() {
|
||||
hook();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A script driving the app gets no network check and no update prompt over its window.
|
||||
@@ -190,20 +257,97 @@ fn checks_for_updates_at_start(control: Option<u16>) -> bool {
|
||||
control.is_none()
|
||||
}
|
||||
|
||||
/// The AppUserModelID a Nightly window is grouped under, set before any native window exists.
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
|
||||
}
|
||||
|
||||
/// A refused Nightly start explains itself in a dialog where there is a desktop to show one.
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("texturecraft: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("texturecraft: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect, and answer the
|
||||
/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the
|
||||
/// launch is already answered and the process returns.
|
||||
fn prepare_launch() -> Option<Vec<OsString>> {
|
||||
let argv: Vec<OsString> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: both are answered here, with nothing but standard output written.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse(argv)
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
if let Profile::NightlyV1(root) = launch_profile::current() {
|
||||
// Every data folder follows the profile before the first one is used.
|
||||
texturecraft_ui_egui::set_data_root(root.clone());
|
||||
texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned());
|
||||
}
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value
|
||||
/// that is not valid Unicode is refused rather than silently replaced.
|
||||
fn launch_arguments(arguments: Vec<OsString>) -> Result<Vec<String>, String> {
|
||||
arguments.into_iter().map(|value| value.into_string().map_err(|_| "an argument is not valid Unicode".to_string())).collect()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`. A
|
||||
// Nightly install is updated by ArtCraft Launcher, so it never installs an update itself.
|
||||
#[cfg(windows)]
|
||||
if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable
|
||||
&& let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
|
||||
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument
|
||||
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with
|
||||
// its own argument. It reads no user state and is started without the profile tokens, so it
|
||||
// runs before the launch protocol would refuse it.
|
||||
#[cfg(windows)]
|
||||
if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) {
|
||||
std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer());
|
||||
}
|
||||
|
||||
let args = match parse_args() {
|
||||
let Some(arguments) = prepare_launch() else { return };
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let args = match launch_arguments(arguments).and_then(parse_args_from) {
|
||||
Ok(Some(a)) => a,
|
||||
Ok(None) => return,
|
||||
Err(e) => {
|
||||
@@ -211,6 +355,12 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// The control server is a stable-install service: a Nightly window is driven by the Launcher,
|
||||
// and its token file would sit in the shared temp folder rather than its private profile.
|
||||
if nightly && args.control.is_some() {
|
||||
eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli");
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
// Errors before the window opens speak the system's language; the app then applies the saved one
|
||||
texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language());
|
||||
@@ -221,11 +371,13 @@ fn main() {
|
||||
previous_hook(info);
|
||||
}));
|
||||
|
||||
// Scripted runs use temporary files so they cannot overwrite saved settings
|
||||
let persistence_path =
|
||||
// Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe
|
||||
// is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the
|
||||
// folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`).
|
||||
let no_prefs_path =
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let ui_file =
|
||||
persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json")));
|
||||
let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron")));
|
||||
let ui_file = no_prefs_path.as_ref().map(|path| path.with_extension("json")).or_else(|| storage_dir().map(|folder| folder.join("ui.json")));
|
||||
if let Some(file) = &ui_file {
|
||||
let _ = ui_state_store::FILE.set(file.clone());
|
||||
}
|
||||
@@ -236,7 +388,11 @@ fn main() {
|
||||
prefs.apply_resource_limits();
|
||||
let session = initial_session(&args);
|
||||
let title_bar = TitleBar::decide(prefs.system_title_bar);
|
||||
let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE);
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_app_id(os_window::app_id())
|
||||
.with_title(os_window::name())
|
||||
.with_inner_size(DEFAULT_SIZE)
|
||||
.with_min_inner_size(MIN_SIZE);
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
@@ -247,8 +403,34 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
let control = args.control;
|
||||
// The Nightly session record: one owner per profile, an unclean exit reported by the next
|
||||
// start, and no document name, path or diagnostic payload collected.
|
||||
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
build_flavor::BUILT_VERSION,
|
||||
Some(env!("TEXTURECRAFT_BUILD_SHA")),
|
||||
) {
|
||||
Ok(state) => state,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, true)
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_window = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The exit hook is the controlled return on macOS, where every quit ends the process inside
|
||||
// AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes.
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
|
||||
};
|
||||
let window_name = os_window::name();
|
||||
let result = eframe::run_native(
|
||||
APP_NAME,
|
||||
window_name,
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
#[cfg(windows)]
|
||||
@@ -258,7 +440,7 @@ fn main() {
|
||||
|
||||
// winit's Quit ends the process without asking; this menu's asks like the close button
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) {
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) {
|
||||
log::warn!("the app menu could not be installed: {e}");
|
||||
}
|
||||
let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
@@ -268,14 +450,27 @@ fn main() {
|
||||
if let Some(port) = control {
|
||||
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
|
||||
}
|
||||
if previous_nightly_unclean || session_health_warning {
|
||||
use texturecraft_ui_egui::i18n::tr;
|
||||
app.banner = Some(if previous_nightly_unclean {
|
||||
tr("The previous TextureCraft Nightly session did not finish normally. No diagnostics have been sent.")
|
||||
} else {
|
||||
tr("TextureCraft Nightly could not record session health in its profile; abnormal-exit detection is unavailable.")
|
||||
});
|
||||
notice_shown_in_window.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
Ok(Box::new(Shell {
|
||||
app,
|
||||
window_frame,
|
||||
exit_hook: Some(Box::new(finish_at_exit)),
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
}))
|
||||
}),
|
||||
);
|
||||
// A controlled return, including a handled startup error. On macOS a window already finished in
|
||||
// its exit hook, so this is then a no-op.
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
if let Err(e) = result {
|
||||
fatal(&e.to_string(), true);
|
||||
std::process::exit(1);
|
||||
@@ -284,7 +479,7 @@ fn main() {
|
||||
|
||||
/// The file startup errors and crashes are appended to, beside the saved settings.
|
||||
fn error_log() -> Option<std::path::PathBuf> {
|
||||
eframe::storage_dir(APP_NAME).map(|d| d.join("errors.log"))
|
||||
storage_dir().map(|d| d.join("errors.log"))
|
||||
}
|
||||
|
||||
/// Append a line with the time (Unix seconds) and the app version; true when it was written.
|
||||
@@ -305,7 +500,7 @@ fn fatal(msg: &str, dialog: bool) {
|
||||
let saved = log.map(|f| format!("\n\n{}", trf("Details saved to {file}", &[("file", &f.display())]))).unwrap_or_default();
|
||||
rfd::MessageDialog::new()
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_title(APP_NAME)
|
||||
.set_title(os_window::name())
|
||||
.set_description(format!("{}\n\n{msg}{saved}", tr("TextureCraft had to close:")))
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
@@ -330,6 +525,55 @@ mod tests {
|
||||
assert_eq!(args.gpu.as_deref(), Some("3080"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_settings_stay_in_the_folder_eframe_used_before_the_app_id() {
|
||||
let legacy = std::path::PathBuf::from("/legacy/TextureCraft");
|
||||
// Stable, no wrapper folder: the folder eframe picked for `APP_NAME` before `with_app_id`
|
||||
// existed, so `app.ron` (window state and the export presets stored in it) does not move.
|
||||
let folder = settings_folder(None, None, Some(legacy.clone())).expect("a legacy folder");
|
||||
assert_eq!(folder.join("app.ron"), legacy.join("app.ron"));
|
||||
// A Stable wrapper's data folder still wins, which is what #801's packaging expects.
|
||||
let wrapper = std::path::PathBuf::from("/wrapper/data");
|
||||
assert_eq!(settings_folder(None, Some(wrapper.clone()), Some(legacy.clone())), Some(wrapper.clone()));
|
||||
// A Nightly profile wins over both, so no Stable folder is ever read.
|
||||
assert_eq!(settings_folder(Some(std::path::Path::new("/profile")), Some(wrapper), Some(legacy)), Some(std::path::PathBuf::from("/profile")));
|
||||
// Nothing resolvable: there is no folder to fall back to and eframe keeps its own default.
|
||||
assert_eq!(settings_folder(None, None, None), None);
|
||||
// The app's wiring: with no profile and no wrapper folder, `app.ron` sits beside `ui.json`
|
||||
// in eframe's folder for `APP_NAME`, not in the folder of the app id `with_app_id` sets.
|
||||
if std::env::var_os(DATA_DIR_ENV).is_none()
|
||||
&& !launch_profile::current().is_nightly()
|
||||
&& let Some(stable) = eframe::storage_dir(APP_NAME)
|
||||
{
|
||||
assert_eq!(storage_dir(), Some(stable.clone()));
|
||||
assert_eq!(storage_dir().map(|dir| dir.join("app.ron")), Some(stable.join("app.ron")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_after_the_delimiter_is_a_file_even_when_it_looks_like_an_option() {
|
||||
let args = parse_args_from(["--".to_string(), "--version".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.file.as_deref(), Some("--version"));
|
||||
let args = parse_args_from(["--".to_string(), "--launch-profile".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.file.as_deref(), Some("--launch-profile"));
|
||||
// Options before the delimiter still parse as options.
|
||||
let args = parse_args_from(["--gpu".to_string(), "nvidia".to_string(), "--".to_string(), "a.glb".to_string()]).unwrap().unwrap();
|
||||
assert_eq!((args.gpu.as_deref(), args.file.as_deref()), (Some("nvidia"), Some("a.glb")));
|
||||
// One window opens one project: extra files after the delimiter are ignored, in that order.
|
||||
let args = parse_args_from(["--".to_string(), "a.glb".to_string(), "b.glb".to_string()]).unwrap().unwrap();
|
||||
assert_eq!(args.file.as_deref(), Some("a.glb"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_arguments_refuse_a_name_that_is_not_unicode() {
|
||||
assert_eq!(launch_arguments(vec![OsString::from("--version")]).unwrap(), vec!["--version".to_string()]);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt as _;
|
||||
assert!(launch_arguments(vec![OsString::from_vec(vec![b'a', 0xff, b'b'])]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_invalid_gpu_args() {
|
||||
assert!(parse_args_from(["--gpu".to_string()]).is_err());
|
||||
@@ -410,6 +654,7 @@ mod tests {
|
||||
let mut harness = builder.build_eframe(|cc| Shell {
|
||||
app: TextureCraftApp::new(cc, session),
|
||||
window_frame: None,
|
||||
exit_hook: None,
|
||||
#[cfg(target_os = "macos")]
|
||||
movable: None,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
//! App-private Nightly session health, not telemetry and not a Launcher protocol.
|
||||
//!
|
||||
//! A live owner holds a separate persistent lease; a secondary launch never rewrites its record.
|
||||
//! Dropping the guard does not clear the marker; only the app's controlled return path does.
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` without ever following a link at the destination: the temporary file is
|
||||
/// created exclusively beside it and renamed over the name, which replaces a link rather than
|
||||
/// writing through it (the engine's `write_atomic` deliberately resolves the target instead).
|
||||
fn write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
let parent = path.parent().ok_or_else(|| io::Error::other("the Nightly record has no folder"))?;
|
||||
let name = path.file_name().and_then(|name| name.to_str()).ok_or_else(|| io::Error::other("the Nightly record name is not Unicode"))?;
|
||||
let temporary = parent.join(format!(".{name}.{}.tmp", std::process::id()));
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt as _;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let staged = write_staged(&mut options, &temporary, bytes).and_then(|()| std::fs::rename(&temporary, path));
|
||||
if let Err(error) = staged {
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
return Err(error);
|
||||
}
|
||||
// The rename is durable only once its folder is synced (no-op where the platform has no handle).
|
||||
#[cfg(unix)]
|
||||
if let Ok(folder) = File::open(parent) {
|
||||
let _ = folder.sync_all();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the whole file and flush it to the device before it may replace the destination.
|
||||
fn write_staged(options: &mut std::fs::OpenOptions, temporary: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
let mut file = options.open(temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
|
||||
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
|
||||
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
|
||||
/// still runs for a start that created no window.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage, while
|
||||
/// Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is Stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed it
|
||||
/// yet, the record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// A handled startup error is a controlled return too. An unwind, abort, forced exit or killed
|
||||
/// process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The next start still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), "next", None).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Set the immutable Nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged, so MSI shortcut
|
||||
//! matching keeps working.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct IdentityError(pub String);
|
||||
|
||||
impl fmt::Display for IdentityError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentityError {}
|
||||
|
||||
/// The AppUserModelID the taskbar groups the Nightly window under, distinct from Stable's.
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
//!
|
||||
//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error
|
||||
//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export
|
||||
//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the
|
||||
//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it,
|
||||
//! or when it is not writable.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// The folder names the launch checks use for this app in each platform's location.
|
||||
const BRAND: &str = "TextureCraft";
|
||||
/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak).
|
||||
const STABLE_ID: &str = "ai.storyteller.texturecraft";
|
||||
/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that
|
||||
/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts.
|
||||
const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly";
|
||||
/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder
|
||||
/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called.
|
||||
const LINUX_STORAGE_BRAND: &str = "texturecraft";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
/// Whether one path is the other or contains it (in either direction), compared component by
|
||||
/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not
|
||||
/// inside `TextureCraft`.
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
/// The running install: never let the profile live inside it (it would be replaced or removed by
|
||||
/// the next update).
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned bundle, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it
|
||||
/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`.
|
||||
fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
|
||||
let home = match platform {
|
||||
Platform::Windows => required_base(env, "USERPROFILE")?,
|
||||
_ => required_base(env, "HOME")?,
|
||||
};
|
||||
Ok(home.join("Documents").join(BRAND))
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
// eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's
|
||||
// per-machine and any per-user install folders. A custom install folder is covered by the
|
||||
// executable's own folder below.
|
||||
let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::<Result<Vec<_>, _>>()?;
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join(BRAND));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
// The four XDG roots carry eframe's settings, caches and state under the app's name.
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND)))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
// eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`,
|
||||
// `ui.json` and `errors.log`: it folds the name, so it is the lowercase one.
|
||||
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND));
|
||||
roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its own per-app data folder.
|
||||
roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}")));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support").join(BRAND),
|
||||
library.join("Caches").join(BRAND),
|
||||
library.join("Caches").join(STABLE_ID),
|
||||
library.join("Preferences").join(BRAND),
|
||||
library.join("Preferences").join(format!("{STABLE_ID}.plist")),
|
||||
library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")),
|
||||
home.join("Applications").join(format!("{BRAND}.app")),
|
||||
PathBuf::from("/Applications").join(format!("{BRAND}.app")),
|
||||
]
|
||||
}
|
||||
};
|
||||
// The user's own documents folder is Stable's default data folder on every platform; a profile
|
||||
// there would share autosaves, smart materials and presets with it.
|
||||
roots.push(default_data_folder(platform, env)?);
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
/// An entry inside the profile must resolve inside it, so a link planted there cannot point
|
||||
/// Nightly's writes at another app's files.
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve
|
||||
/// inside it.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The app's writable probe: create a file exclusively in the profile and remove it again.
|
||||
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
|
||||
let probe = dir.join("exclusive-write-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
}
|
||||
|
||||
/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only
|
||||
/// access where the platform has it, and return the resolved root to use.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
// A native package must not carry another app's Flatpak namespace, and the Nightly bundle must
|
||||
// be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its
|
||||
// `~/.var/app/<nightly id>` sandbox is separate from stable's, so only other ids are refused.
|
||||
if platform != Platform::Windows
|
||||
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
|
||||
&& id != NIGHTLY_ID
|
||||
{
|
||||
return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect any of its folders elsewhere.
|
||||
entries_stay_inside(&chosen)?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate =
|
||||
std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/texturecraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
|
||||
fn profile(&self, name: &str) -> PathBuf {
|
||||
self.root.join("profiles").join(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory this fixture created is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_private_profile_is_created_and_returned_resolved() {
|
||||
let fixture = Fixture::new();
|
||||
let profile = fixture.profile("nightly");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert_eq!(fixture.check(platform, &profile).unwrap(), profile);
|
||||
assert!(profile.is_dir());
|
||||
std::fs::remove_dir_all(&profile).ok();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let home = fixture.home();
|
||||
let candidates: Vec<(Platform, PathBuf)> = vec![
|
||||
(Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)),
|
||||
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)),
|
||||
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)),
|
||||
(Platform::Windows, home.join("Documents").join(BRAND)),
|
||||
(Platform::Linux, home.join(".config").join(BRAND)),
|
||||
(Platform::Linux, home.join(".local/share").join(BRAND)),
|
||||
(Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)),
|
||||
(Platform::Linux, home.join(".cache").join(BRAND)),
|
||||
(Platform::Linux, home.join(".local/state").join(BRAND)),
|
||||
(Platform::Linux, home.join("Documents").join(BRAND)),
|
||||
(Platform::Linux, PathBuf::from("/usr/bin/texturecraft")),
|
||||
(Platform::Linux, PathBuf::from("/opt/texturecraft")),
|
||||
(Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))),
|
||||
(Platform::Mac, home.join("Library/Application Support").join(BRAND)),
|
||||
(Platform::Mac, home.join("Library/Caches").join(BRAND)),
|
||||
(Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))),
|
||||
(Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))),
|
||||
(Platform::Mac, home.join("Documents").join(BRAND)),
|
||||
(Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))),
|
||||
];
|
||||
for (platform, stable) in candidates {
|
||||
for candidate in [stable.clone(), stable.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{platform:?} accepted {}", candidate.display());
|
||||
assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_running_install_is_fenced_on_every_platform() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
let inside = fixture.exe.parent().unwrap().join("profile");
|
||||
assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookalike_names_are_not_overlaps_but_case_folding_is() {
|
||||
let fixture = Fixture::new();
|
||||
let documents = fixture.home().join("Documents");
|
||||
assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder");
|
||||
assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly");
|
||||
for platform in [Platform::Windows, Platform::Mac] {
|
||||
assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_parent_traversal_and_empty_roots_are_refused() {
|
||||
let fixture = Fixture::new();
|
||||
for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] {
|
||||
assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_nightly_flatpak_may_start_with_its_own_id() {
|
||||
let fixture = Fixture::new();
|
||||
let profile = fixture.profile("flatpak");
|
||||
assert!(fixture.check(Platform::Linux, &profile).is_ok());
|
||||
std::fs::remove_dir_all(&profile).ok();
|
||||
let check_with = |id: &str, candidate: &Path| {
|
||||
let id = OsString::from(id);
|
||||
validate_for(
|
||||
Platform::Linux,
|
||||
candidate,
|
||||
|key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) },
|
||||
Some(&fixture.exe),
|
||||
ensure_writable,
|
||||
)
|
||||
};
|
||||
// Stable's id, its window id and an unrelated app's id are all refusals.
|
||||
for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] {
|
||||
assert!(check_with(id, &profile).is_err(), "{id} was accepted");
|
||||
}
|
||||
// The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the
|
||||
// profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`).
|
||||
let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}"));
|
||||
let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly");
|
||||
assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed);
|
||||
std::fs::remove_dir_all(&sandbox).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_entry_that_leaves_the_profile_is_refused() {
|
||||
let fixture = Fixture::new();
|
||||
let profile = fixture.profile("aliased");
|
||||
let outside = fixture.root.join("somewhere else");
|
||||
std::fs::create_dir_all(&profile).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused");
|
||||
// A dangling link is not a missing folder that may be created.
|
||||
std::fs::remove_file(profile.join("autosave")).unwrap();
|
||||
std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &profile).is_err());
|
||||
std::fs::remove_file(profile.join("logs")).unwrap();
|
||||
// A plain folder inside it is fine.
|
||||
std::fs::create_dir(profile.join("autosave")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &profile).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_write_probe_never_falls_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let profile = fixture.profile("read only");
|
||||
let reached = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&profile,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
|_| {
|
||||
reached.set(true);
|
||||
Err(std::io::Error::other("read-only filesystem"))
|
||||
},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(reached.get());
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
// The app must not then use the stable folder: it simply refuses to start.
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() {
|
||||
let fixture = Fixture::new();
|
||||
let real = fixture.root.join("real profiles");
|
||||
std::fs::create_dir_all(&real).unwrap();
|
||||
let link = fixture.root.join("linked");
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
// A link to a private folder is fine, and the resolved root is what the app uses.
|
||||
let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap();
|
||||
assert_eq!(resolved, real.join("nightly"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user