diff --git a/Cargo.lock b/Cargo.lock index 01e17558..2c2a5d6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,6 +1324,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5949,6 +5957,7 @@ dependencies = [ "craft-host", "craft-image-codecs", "craft-menu", + "craft-nightly", "craft-update", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index bb398c92..2a15ba96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index ab29d036..c9be2510 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -25,6 +25,8 @@ log = { workspace = true } rfd = { workspace = true } # Pass the selected window backend to the title bar and UI runtime craft-host = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs index 294f1e19..9330b7d8 100644 --- a/apps/texturecraft/src/build_flavor.rs +++ b/apps/texturecraft/src/build_flavor.rs @@ -1,14 +1,9 @@ //! 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, -} +pub use craft_nightly::BuildFlavor; /// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor /// 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 { @@ -58,22 +44,6 @@ mod tests { 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); diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 84f5061f..9e29c559 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -1,126 +1,30 @@ -//! 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. +//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`. +//! +//! 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, -} - -static PROFILE: OnceLock = OnceLock::new(); +pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().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) -> Result { - 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) -> Result { - 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, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root +/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly +/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root ` pair), and +/// install the resolved [`Profile`] into the process-wide `OnceLock`. +pub fn prepare(flavor: BuildFlavor, args: Vec) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use std::path::PathBuf; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -130,88 +34,93 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = crate::profile_root::spec(); 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 }); + let launch = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[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(); + fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root"); + let argv = args(&["model.glb", "--gpu", "nvidia"]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, argv); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_launcher_flags_override_canonical_root_and_preserve_files() { + let spec = crate::profile_root::spec(); + let argv = args(&[ + craft_nightly::LAUNCH_PROFILE_FLAG, + craft_nightly::NIGHTLY_V1_CONTRACT, + craft_nightly::PROFILE_ROOT_FLAG, + absolute(), + "--", + "--profile-root", + "model with spaces.glb", + ]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn invalid_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT]), 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", "--"]), + args(&[ + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--profile-root", + absolute(), + "--", + ]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).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]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = crate::profile_root::spec(); 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()); - } + let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); - #[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()); - } + let launcher = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(launcher.is_version_query(), "launcher {flag}"); + } - #[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()); + let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 678c0a8c..0255487b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) { } } -/// 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. +/// Select the immutable launch profile before any startup service or side effect, and answer +/// 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> { let argv: Vec = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --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)) { + // Plain `--version` / `-V` is answered immediately with nothing but standard output written, + // even in a minimal environment without home/data variables. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::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::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Launcher's `--launch-profile nightly-v1 --profile-root --version`: `craft-nightly` + // skips root validation and profile installation for version queries. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { 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)) { + if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) { report_launch_profile_error(&error); std::process::exit(2); } @@ -326,7 +324,7 @@ fn prepare_launch() -> Option> { 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) + Some(early.passthrough_args) } /// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index db10fdae..7ab39c60 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -1,567 +1,223 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! App-owned nightly profile specification backed by `craft-nightly`. //! -//! 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. +//! A Nightly profile holds *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. +//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and +//! writability probe using the TextureCraft-specific boundaries declared here. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -/// The folder names the launch checks use for this app in each platform's location. +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier used for the default nightly profile path. +pub const APP_ID: &str = "texturecraft"; +/// Human-readable application name and stable folder name. 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 { - 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 { - 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, key: &str) -> Result { - 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, key: &str, fallback: &str) -> Result { - 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 { - 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::>() - }; - 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 { - 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) -> Result { - 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, exe: &Path) -> Result, 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::, _>>()?; - 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::, _>>()?; - // 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, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let entry = chosen.join(name); - let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?; - if !metadata.is_dir() { - return Err(format!("the nightly {label} must be a directory inside its selected profile")); - } - let child = canonical_future(&entry)?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} +/// 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`). +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// Known folder-only entries directly inside a Nightly profile. -const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; +const PROFILE_FOLDERS: &[&str] = &["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; -/// 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}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) +/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment. +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); - } +/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup. +pub fn spec_with_env(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: BRAND, + stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND], + stable_package_id: STABLE_ID, + nightly_package_id: NIGHTLY_ID, + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(&env), } - #[cfg(windows)] - { - use winsafe::{HFILE, co}; - let (file, _) = HFILE::CreateFile( - path.to_str().ok_or("the nightly profile file path is not textual")?, - co::GENERIC::default(), - Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), - None, - co::DISPOSITION::OPEN_EXISTING, - co::FILE_ATTRIBUTE::NORMAL, - Some(co::FILE_FLAG::OPEN_REPARSE_POINT), - None, - None, - ) - .map_err(|e| e.to_string())?; - let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; - if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { - return Err("the nightly profile file must not be an alias or directory".into()); - } - if info.nNumberOfLinks != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - let _ = (path, metadata); - 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) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// 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, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} +/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that +/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`. +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - 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/` 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 + // 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. + #[cfg(target_os = "windows")] + if let Some(home) = non_empty_abs_env(env, "USERPROFILE") { + roots.push(home.join("Documents").join(BRAND)); + } + #[cfg(not(target_os = "windows"))] + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join("Documents").join(BRAND)); + } + + #[cfg(target_os = "windows")] { - return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join(BRAND)); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(env, key) { + roots.push(base.join(BRAND)); + } + } } - 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)] + + #[cfg(target_os = "linux")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join(format!(".var/app/{STABLE_ID}"))); + } } - 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()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist"))); + roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState"))); + roots.push(home.join("Applications").join(format!("{BRAND}.app"))); + } + roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app"))); } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + roots } #[cfg(test)] mod tests { use super::*; + use craft_nightly::{ProfileError, validate_and_prepare_root}; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, + struct TempDir { + path: PathBuf, } - impl Fixture { - fn new() -> Self { + impl TempDir { + fn new(label: &str) -> 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))); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let path = loop { + let candidate = base.join(format!("texturecraft-profile-spec-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Ok(()) => break candidate, 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 } + Self { path } } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - 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) + fn path(&self) -> &Path { + &self.path } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.path); } } #[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(); + fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() { + let tmp = TempDir::new("spec"); + let home = tmp.path().join("home"); + let mut env = BTreeMap::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("USERPROFILE", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string()); + env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, "texturecraft"); + assert_eq!(spec.display_name, "TextureCraft"); + assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert!(spec.forbidden_env_vars.is_empty()); + assert!(spec.portable_markers.is_empty()); + assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND))); + + #[cfg(target_os = "linux")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}")))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app")))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app")))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND))); + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND))); } } #[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()); - } + fn nightly_profile_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let private = tmp.path().join("nightly-profile"); + let spec = spec_with_env(|_| None); + + let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile"); + assert_eq!(canonical, private); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + + assert_eq!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); } } #[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"); - } - } + fn documents_data_folder_is_refused() { + let tmp = TempDir::new("documents"); + let home = tmp.path().join("home"); + let documents_stable = home.join("Documents").join(BRAND); + let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string())); - #[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] - fn nightly_profile_reopens_after_saving_settings_and_session_state() { - let fixture = Fixture::new(); - for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { - let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); - assert_eq!(fixture.check(platform, &private).unwrap(), private); - for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } - } - - #[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")); + assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); } } diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index c5cd5f3f..cc2ffbc0 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -123,6 +123,8 @@ impl<'a> Source<'a> { } } +/// The material's base colour at `uv` (bilinear, wrapping), sRGB RGBA times its factor; white +/// where there is no texture or the UV is not finite. fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let sampled_color = if material.texels.is_empty() || !uv.is_finite() { Vec4::ONE @@ -134,11 +136,31 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) }; let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + if fx.is_finite() && fy.is_finite() { + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + let (x1, y1) = (x.saturating_add(1), y.saturating_add(1)); + texel(x, y).lerp(texel(x1, y), tx).lerp(texel(x, y1).lerp(texel(x1, y1), tx), ty) + } else { + Vec4::ONE + } }; let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Sampling at huge but finite UVs returns a finite colour instead of overflowing. + #[test] + fn base_color_sampling_survives_huge_finite_uvs() { + let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; + for uv in [Vec2::new(1.0e30, 0.5), Vec2::new(0.5, -1.0e30), Vec2::splat(f32::MAX), Vec2::splat(1.0e6)] { + let c = base_color(&material, uv); + assert!(c.is_finite(), "{uv}: {c}"); + } + } +} diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 781797d2..893f9429 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -578,6 +578,9 @@ impl Session { self.doc = stroke.before; return Ok(()); } + if self.painting_paths { + self.path_tiles.extend(stroke.canvas.dirty.iter().copied()); + } let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone()); if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, stencil_allows_stroke) { @@ -695,6 +698,9 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> { + if self.painting_paths { + self.path_tiles.extend(canvas.dirty.iter().copied()); + } if self.quick_mask.editing { return self.paint_fill(ts, canvas, gray); } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 0413477b..15455941 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use texturecraft_compose::{PaintTarget, PixelStore}; +use texturecraft_compose::{ImageRes, PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; @@ -26,6 +26,9 @@ use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go +/// first. +const CACHE_BYTES: usize = 256 << 20; /// The undo step that adds a new path pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). @@ -151,23 +154,143 @@ impl PathState { } } -/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and -/// texture size they were painted for. +/// Mesh id, texture size, owner layer channels, texture set channels. +type CacheKey = (u64, Option<(u32, u32)>, Vec, Vec); +/// A path sublayer's images: its mask (`None`) and each channel. +type Snap = BTreeMap, TileImage>; +/// A stored path and the brush alpha image it was painted with. +type Painted = (PathShape, Option>); + +/// A path sublayer as last painted for `key`: its paths, its images after each path +/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that +/// path changed; None once [`evict`]ed) and the tiles each path painted. #[derive(Clone)] pub(crate) struct PathCache { pub(crate) eid: LayerId, - // Session::invalidate_changed discards the prefix when an image it reads changes - key: (u64, Option<(u32, u32)>), - below: Vec, - mask: Option, - layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, + key: CacheKey, + shapes: Vec, + snaps: Vec>, + tiles: Vec>, +} + +/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the +/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until +/// one writes, so a snapshot that diverged from the live image holds its own. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + if seen.insert(img.table_id()) { + bytes += img.table_bytes(); + } + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + +/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent +/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +/// Returns the bytes the kept snapshots are charged. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) -> usize { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } + let mut bytes = 0; + for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; + } + } + bytes +} + +/// Runs [`evict`] only when the snapshots may have outgrown the budget. `evict` charges every +/// kept snapshot, so calling it after each appended path made a repaint of n paths cost n +/// scans of up to n snapshots. A snapshot differs from the one before it only in the tiles its +/// path painted, so those tiles bound what it adds: `held` is an upper bound on the bytes +/// charged, and the scan runs once it passes the budget (then `held` is exact again). +struct EvictPacer { + held: usize, +} + +impl EvictPacer { + /// Scan the snapshots kept from the previous repaint once, trimming them to the budget. + fn start(snaps: &mut [Option], edited: usize) -> Self { + Self { held: evict(snaps, CACHE_BYTES, edited) } + } + + /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. + fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { + let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); + // The new snapshot may also own a table per image (a write after the clone copies it). + let table_bytes: usize = state.values().map(TileImage::table_bytes).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes); + if self.held > CACHE_BYTES { + self.held = evict(snaps, CACHE_BYTES, edited); + } + } +} + +fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (x, y) => x.is_none() && y.is_none(), + } +} + +fn same_path(a: &Painted, b: &Painted) -> bool { + a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref()) +} + +/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always +/// gives it a new one); a missing image reads as empty. +fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool { + a.keys().chain(b.keys()).all(|k| { + let (x, y) = (a.get(k), b.get(k)); + let dims = |i: &TileImage| (i.width(), i.height(), i.comps()); + x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y)) + && tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty)))) + }) +} + +/// Copy `from`'s tiles at `tiles` into `to`. +fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) { + for (k, src) in from { + to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps())); + } + for (k, dst) in to.iter_mut() { + let src = from.get(k); + for &(x, y) in tiles { + dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned()); + } + } } impl PathCache { /// The image resources the cached paths painted their mask with pub(crate) fn images(&self) -> impl Iterator + '_ { - // Only successfully painted paths enter the prefix - self.below.iter().filter_map(|shape| shape.paint.get("mask_image")?.as_str()) + self.shapes.iter().filter_map(|(shape, _)| shape.paint.get("mask_image")?.as_str()) } } @@ -363,7 +486,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid, index) + s.render_paths(eid) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -612,7 +735,7 @@ impl Session { if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) { paths.remove(index); } - session.render_paths(effect, index) + session.render_paths(effect) }, )?; self.cancel_path(); @@ -981,44 +1104,65 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before - /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are - /// cached for the next repaint otherwise, so editing a path repaints it and the paths above - /// only. Runs inside the caller's undo step. Returns each painted path's report (null for - /// the cached ones). - fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the + /// paths before the first changed one keep their pixels, and an unchanged path above it + /// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs + /// inside the caller's undo step. Returns each painted path's report (null for the cached + /// ones). + fn render_paths(&mut self, eid: LayerId) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); - let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); - self.doc.pixels.masks.remove(&eid); - self.doc.pixels.layers.retain(|(id, _), _| *id != eid); - let start = match &self.path_cache { - Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { - if let Some(m) = &c.mask { - self.doc.pixels.masks.insert(eid, m.clone()); - } - self.doc.pixels.layers.extend(c.layers.iter().cloned()); - c.below.len() - } - _ => 0, - }; + let images = &self.images; + let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned()); + let new: Vec = shapes + .into_iter() + .map(|sh| { + let a = alpha(&sh); + (sh, a) + }) + .collect(); + let project = &self.doc.project; + let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default(); + let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set); + let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key); + let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| { + let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count(); + (p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count()) + }); + // Start from the last snapshot kept at or below the first changed path (the first one, + // empty, is always kept). + let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0)); + let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); + let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); + let mut state = snaps[start].clone().unwrap_or_default(); + let mut pacer = EvictPacer::start(&mut snaps, prefix); // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). let mut out = vec![Value::Null; start]; let result = self.while_painting_paths(eid, |s| { let mut result = Ok(()); - for i in start..=shapes.len() { - if i == from.min(shapes.len()) && i > start { - let pixels = &s.doc.pixels; - let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); - s.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + for (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, c.tiles[o].len()); + out.push(Value::Null); + continue; } - let Some(sh) = shapes.get(i) else { break }; + s.put_snap(eid, &state); + s.path_tiles.clear(); match s.paint_shape(sh) { Ok(v) => out.push(v), Err(e) => { @@ -1026,9 +1170,17 @@ impl Session { break; } } + state = s.take_snap(eid); + tiles.push(std::mem::take(&mut s.path_tiles)); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, tiles.last().map_or(0, BTreeSet::len)); } + s.put_snap(eid, &state); result }); + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } result.map(|_| out) } @@ -1054,6 +1206,24 @@ impl Session { } } + fn take_snap(&self, eid: LayerId) -> Snap { + let p = &self.doc.pixels; + let mask = p.masks.get(&eid).map(|m| (None, m.clone())); + mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect() + } + + fn put_snap(&mut self, eid: LayerId, snap: &Snap) { + let p = &mut self.doc.pixels; + p.masks.remove(&eid); + p.layers.retain(|(id, _), _| *id != eid); + for (k, img) in snap { + match k { + None => p.masks.insert(eid, img.clone()), + Some(c) => p.layers.insert((eid, *c), img.clone()), + }; + } + } + fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; let (camera, viewport) = paint_view(shape, &paint); @@ -1230,45 +1400,246 @@ mod tests { v } - #[test] - fn cached_repaint_matches_a_full_repaint() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + /// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture. + fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap(); s.update(); execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); let mut eid = 0; - for v in [0.2, 0.5, 0.8] { - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + for v in rows { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap(); eid = r["committed"]["effect"].as_u64().unwrap(); } - let eid = texturecraft_core::LayerId(eid); + (s, texturecraft_core::LayerId(eid)) + } - // Live edits of the middle path reuse the bottom path's pixels - execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); - for v in [0.4, 0.45] { - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); - } - - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); - - let r = s.render_paths(eid, 1).unwrap(); - - assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); - - let cached = pixels(&s, eid); + /// Move path `index` to row `v` (a live edit) and check the result against painting every + /// path. Returns which paths were repainted. + fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec { + execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap(); + let before = s.path_cache.clone(); + execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + let cached = pixels(s, eid); + s.path_cache = before; + let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect(); + assert_eq!(cached, pixels(s, eid)); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); - - assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + s.stop_path_edit(); + painted + } + #[test] + fn cached_repaint_matches_a_full_repaint() { + // Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows. + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints"); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles"); + assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); + } + + #[test] + fn a_filled_path_above_an_edit_keeps_its_tiles() { + // The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles. + let (mut s, eid) = with_paths(&[0.2]); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true})) + .unwrap(); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels"); + } + + #[test] + fn removing_a_path_keeps_the_paths_above() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let before = s.path_cache.clone(); + execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap(); + let cached = pixels(&s, eid); + s.path_cache = before; + assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache"); + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + } + + #[test] + fn replacing_the_brush_alpha_image_repaints() { + let (mut s, eid) = with_paths(&[0.2]); + let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes::new(2, 2, vec![[v; 4]; 4], false)); + s.images.insert("a".into(), img(1.0)); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap(); + s.render_paths(eid).unwrap(); + s.images.insert("a".into(), img(0.5)); + let r = s.render_paths(eid).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}"); + } + + #[test] + fn snapshots_stay_within_the_budget() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, usize::MAX, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4); + // The paths are on different tiles, so a snapshot costs nothing beyond its own tile table + // (the tiles are all shared with the live pixels): a budget of two tables keeps them. + let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, 2 * table, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; + // Appending still paints the new path alone. + let shape = s.paths(eid).unwrap()[0].clone(); + if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { + v.push(shape); + } + let r = s.render_paths(eid).unwrap(); + assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); + // Editing above evicted snapshots repaints from the bottom and matches a full repaint. + let c = s.path_cache.as_mut().unwrap(); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); + assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); + // That edit kept the snapshot below path 3 within a one-table budget: its next frame starts + // there, and the snapshots above it that cost only a table keep their paths unrepainted. + let c = s.path_cache.as_mut().unwrap(); + let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, table, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); + } + + #[test] + fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; + let mut pacer = super::EvictPacer::start(&mut snaps, 0); + assert_eq!(pacer.held, 0, "the first and last snapshots are free"); + // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). + for n in 1..=3 { + pacer.appended(&mut snaps, 0, &empty, 1); + assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths"); + } + // Past the budget the estimate gives way to an exact scan. + pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); + assert!(pacer.held < super::CACHE_BYTES, "scanned: {}", pacer.held); + } + + #[test] + fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with + // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &all); + let s3 = painted(&s2, &[(0, 0)]); + let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())]; + let kept = |snaps: &[Option]| snaps.iter().map(Option::is_some).collect::>(); + let mut snaps = fresh(); + super::evict(&mut snaps, usize::MAX, 0); + assert_eq!(kept(&snaps), [true; 4]); + let mut snaps = fresh(); + super::evict(&mut snaps, tile_bytes + table, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen"); + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 0); + assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); + // Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own. + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 1); + assert_eq!(kept(&snaps), [true, true, false, true]); + } + + #[test] + fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() { + // Big image: the table (one slot per tile position) outweighs a one-tile stroke. + let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + assert!(table >= 128 * 128 * 8, "table {table}"); + let s1 = painted(&empty, &[(0, 0)]); + let s2 = painted(&s1, &[(1, 0)]); + let s3 = painted(&s2, &[(2, 0)]); + let live = painted(&s3, &[(3, 0)]); + let mut seen = std::collections::BTreeSet::new(); + // Alone, a diverged snapshot holds its own table; charged again with the same table, it is free. + let first = super::charge(&s2, &mut seen); + assert!(first >= table, "charged {first}"); + assert_eq!(super::charge(&s2, &mut seen), 0); + // Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does. + let tile_only = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)]; + super::evict(&mut snaps, 3 * tile_only, 0); + assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots"); + } + + #[test] + fn the_quick_mask_does_not_clip_paths() { + let (mut s, eid) = with_paths(&[0.2, 0.8]); + let plain = pixels(&s, eid); + s.quick_mask.enabled = true; + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(plain, pixels(&s, eid)); + } + + #[test] + fn owner_channel_change_skips_the_cache() { + let (mut s, eid) = with_paths(&[0.3, 0.7]); + s.render_paths(eid).unwrap(); + let owner = s.doc.project.effect(eid).unwrap().0; + let layer = s.doc.project.layer_mut(owner).unwrap(); + let ch = *layer.channels.keys().next().unwrap(); + layer.channels.remove(&ch); + let r = s.render_paths(eid).unwrap(); + assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}"); + assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel"); + } + + #[test] + fn deleting_the_path_effect_releases_its_cached_tiles() { + let (mut s, eid) = with_paths(&[0.2, 0.5, 0.8]); execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap(); - let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); - assert!(cached_tiles > 0); - + let held = |s: &Session| { + s.path_cache.as_ref().map_or(0, |c| c.snaps.iter().flatten().flat_map(|snap| snap.values()).map(|i| i.allocated_count()).sum::()) + }; + assert!(held(&s) > 0); execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); - let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); - assert_eq!(remaining_tiles, 0); + assert_eq!(held(&s), 0); assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles"); } @@ -1292,14 +1663,14 @@ mod tests { execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap(); - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached"); + assert_eq!(s.path_cache.as_ref().map(|c| c.shapes.len()), Some(2), "the paths are cached"); execute(&mut s, "resource.remove", &json!({"name": image})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap(); let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid)); let edited = mask(&s); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); + s.render_paths(eid).unwrap(); assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does"); } @@ -1311,7 +1682,9 @@ mod tests { let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]); let retained = Arc::downgrade(&tile); image.set_tile(0, 0, Some(tile)); - session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() }); + let snap: Snap = [(None, image)].into(); + session.path_cache = + Some(PathCache { eid: LayerId(0), key: (0, None, Vec::new(), Vec::new()), shapes: Vec::new(), snaps: vec![Some(snap)], tiles: Vec::new() }); let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into()))); diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index cfb0175c..15adf404 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -95,10 +95,10 @@ impl Session { } /// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the - /// quick mask is off or being edited). + /// quick mask is off or being edited, and for paths, which repaint from what they store). pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> { let q = &self.quick_mask; - (q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted)) + (q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted)) } /// Commit a stroke into the quick mask of `ts`. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 86b537e0..31b1eca1 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -527,8 +527,10 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, - /// Pixels of the paths below the one being edited, so live edits skip repainting them. + /// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach. pub(crate) path_cache: Option, + /// Tiles painted since `render_paths` cleared it (the footprint of one path). + pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>, /// A new path's live preview: the path becomes an undo step only when it is applied pub(crate) path_draft: Option, /// Point changes of the path being edited: (earlier states for undo, undone states for redo) @@ -620,6 +622,7 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_tiles: Default::default(), path_draft: None, path_steps: Default::default(), path: None, diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 395e6c5e..bd99e01f 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -58,6 +58,9 @@ const QUAD_SECOND_MARK: u8 = 0b001; /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; +/// Largest UV coordinate a mesh may carry (UDIM tiles stop at 10 columns; this is far beyond any +/// real layout). Texel lookups turn UVs into integers, which a UV like 1e30 would overflow. +pub const MAX_UV: f32 = 1.0e6; impl Mesh { pub fn triangle_count(&self) -> usize { @@ -220,6 +223,12 @@ impl Mesh { if self.positions.iter().any(|p| !p.is_finite()) { return Err(GeomError::Invalid("mesh has non-finite positions".into())); } + if self.normals.iter().any(|n| !n.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if self.uvs.iter().any(|uv| !uv.is_finite() || uv.x.abs() > MAX_UV || uv.y.abs() > MAX_UV) { + return Err(GeomError::Invalid(format!("mesh has non-finite UVs or UVs beyond ±{MAX_UV}"))); + } for s in &self.submeshes { if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); @@ -895,6 +904,27 @@ mod tests { assert!(m.validate().is_err()); } + /// Validation rejects non-finite normals and non-finite or beyond-limit UVs, but accepts UDIM-style UVs. + #[test] + fn validate_refuses_non_finite_normals_and_absurd_uvs() { + assert!(quad().validate().is_ok()); + for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1.0e30, -2.0e6] { + let mut m = quad(); + m.uvs[1].x = bad; + assert!(m.validate().is_err(), "uv {bad}"); + let mut m = quad(); + m.uvs[2].y = bad; + assert!(m.validate().is_err(), "uv {bad}"); + } + let mut m = quad(); + m.normals[0].z = f32::NAN; + assert!(m.validate().is_err()); + // Large but real UDIM-style layouts stay valid. + let mut m = quad(); + m.uvs[0] = Vec2::new(1009.5, 0.5); + assert!(m.validate().is_ok()); + } + #[test] fn append_offsets_indices_and_materials() { let mut a = quad(); diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index 78d5b5d2..59e3956d 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -117,6 +117,10 @@ impl Heights { if !(fx.is_finite() && fy.is_finite()) { return 0.0; } + // Past one texel outside, every lookup clamps to the same edge texel, so clamping the + // position first changes no result but keeps `x0 + 1` far from overflowing: a huge finite + // UV saturates the `as isize` cast, and isize is 32 bits on wasm32. + let (fx, fy) = (fx.clamp(-1.0, self.w as f32), fy.clamp(-1.0, self.h as f32)); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); let (x0, y0) = (x0 as isize, y0 as isize); @@ -151,6 +155,22 @@ mod tests { } } + /// Far-off UVs clamp to the nearest edge texel without overflow; NaN gives 0 and in-range sampling is unchanged. + #[test] + fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { + let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; + // x0 + 1 used to overflow for these (the cast to isize saturates at isize::MAX). + for far in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN, 1.0e10] { + assert!(heights.sample(Vec2::new(far, far)).is_finite()); + } + assert_eq!(heights.sample(Vec2::new(1.0e30, 1.0e30)), 4.0); + assert_eq!(heights.sample(Vec2::new(-1.0e30, -1.0e30)), 1.0); + assert_eq!(heights.sample(Vec2::new(1.0e30, -1.0e30)), 2.0); + assert_eq!(heights.sample(Vec2::new(f32::NAN, 0.5)), 0.0); + // In range, bilinear is unchanged: the centre of the 2 x 2 is the mean. + assert!((heights.sample(Vec2::new(0.5, 0.5)) - 2.5).abs() < 1e-6); + } + #[test] fn uniform_height_lifts_the_dense_plane_along_its_normal() { let plane = primitives::plane(2.0, 1); diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index 31e30349..81c96ac7 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -62,6 +62,17 @@ impl TileImage { self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref) } + /// Identity of the shared tile table: clones share it until one of them writes, so two images + /// with the same id hold one allocation (for memory accounting). + pub fn table_id(&self) -> usize { + Arc::as_ptr(&self.tiles) as usize + } + + /// Bytes of the tile table itself (one slot per tile position), not counting the tiles. + pub fn table_bytes(&self) -> usize { + self.tiles.len().saturating_mul(std::mem::size_of::>()) + } + /// Replace a tile wholesale (None frees it). pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option) { let len = TILE_AREA * self.comps; diff --git a/crates/ui-egui/src/autosave_notice.rs b/crates/ui-egui/src/autosave_notice.rs new file mode 100644 index 00000000..5ca18157 --- /dev/null +++ b/crates/ui-egui/src/autosave_notice.rs @@ -0,0 +1,80 @@ +//! Tells the user when an autosave fails: the worker reports back, and one notice stays until a later +//! autosave works, so a missing backup is not mistaken for a saved one. + +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// How one autosave ended. +struct Outcome { + path: PathBuf, + result: Result<(), String>, +} + +pub(crate) struct AutosaveNotice { + sender: Sender, + receiver: Receiver, + /// The failure the user was last told about; cleared by an autosave that works. + shown: Option, +} + +impl Default for AutosaveNotice { + fn default() -> Self { + let (sender, receiver) = channel(); + Self { sender, receiver, shown: None } + } +} + +/// Sends one autosave's result to the app, from any thread. +pub(crate) struct Reporter { + sender: Sender, + context: egui::Context, +} + +impl Reporter { + pub(crate) fn report(self, path: PathBuf, result: Result<(), String>) { + match &result { + Ok(()) => log::info!("autosaved {}", path.display()), + Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), + } + + // A closed channel means the app is gone, so there is nobody left to tell + if self.sender.send(Outcome { path, result }).is_ok() { + self.context.request_repaint(); + } + } +} + +impl AutosaveNotice { + pub(crate) fn reporter(&self, context: &egui::Context) -> Reporter { + Reporter { sender: self.sender.clone(), context: context.clone() } + } +} + +/// Take in finished autosaves. A failure is announced once, however often it repeats. +pub(crate) fn poll(app: &mut TextureCraftApp) { + while let Ok(Outcome { path, result }) = app.autosave_notice.receiver.try_recv() { + let message = result.err().map(|error| trf("Autosave to {path} failed: {error}", &[("path", &path.display()), ("error", &error)])); + if message == app.autosave_notice.shown { + continue; + } + + if let Some(old) = app.autosave_notice.shown.take() { + app.toasts.retain(|toast| toast.text != old); + } + + if let Some(message) = &message { + app.session.log.error("Autosave", message.clone()); + app.toast_sticky(message.clone()); + + // The user's focus is elsewhere, so a screen reader hears the notice only as a live region + if let Some(toast) = app.toasts.last_mut() { + toast.announce = true; + } + } + + app.autosave_notice.shown = message; + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cec3e28b..9f98d144 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -15,6 +15,8 @@ mod ask; mod auto_rebake; #[cfg(not(target_arch = "wasm32"))] mod autosave_name; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_notice; mod bake_job; pub mod bake_mode; mod bake_preset; @@ -403,6 +405,8 @@ pub struct TextureCraftApp { /// The dialog opening that owns the Project name widget's undo state. #[cfg(not(target_arch = "wasm32"))] project_name_editor_opening: Option, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: autosave_notice::AutosaveNotice, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -557,6 +561,8 @@ impl TextureCraftApp { unsaved_autosave_file: None, #[cfg(not(target_arch = "wasm32"))] project_name_editor_opening: None, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: Default::default(), styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -1200,7 +1206,7 @@ impl TextureCraftApp { /// Every `prefs.autosave_minutes`, write a modified project to the autosave folder (encoded /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] - fn autosave(&mut self, now: f64) { + fn autosave(&mut self, ctx: &egui::Context, now: f64) { if self.save_job.is_some() { return; } @@ -1225,19 +1231,20 @@ impl TextureCraftApp { let dir = user_dir("autosave"); let path = self.autosave_path(&dir); let snapshot = self.session.project_snapshot(); + let reporter = self.autosave_notice.reporter(ctx); + let spawn_reporter = self.autosave_notice.reporter(ctx); + let target = path.clone(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); - drop(reservation); - match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), - } + // Report while the reservation still holds off the next autosave, so results arrive in the order of the attempts + reporter.report(path, result); + drop(reservation); }); if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); + spawn_reporter.report(target, Err(e.to_string())); } } } @@ -1390,7 +1397,8 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] { self.poll_save(ctx); - self.autosave(now); + self.autosave(ctx, now); + autosave_notice::poll(self); } i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c74a956a..702cca51 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -5,7 +5,7 @@ use std::ops::RangeInclusive; use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; -use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS, shown_value}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -168,7 +168,11 @@ impl PropertySheet<'_> { } let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); - let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); + + // Reserve for track values while still measuring any wider typed value on display + self.measure_track_values(&slider.range, |end| shown_value(end, slider.decimals, slider.suffix)); + let shown = shown_value(*slider.value, slider.decimals, slider.suffix); + let typed = self.column_value_field(id, &slider.label, center_y, &shown, slider.suffix, *slider.value, &slider.typed, slider.decimals); *edit = Self::apply_typed(slider.value, typed, dragged); y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; } diff --git a/crates/ui-egui/src/property_sheet/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs index eddf9f72..550223df 100644 --- a/crates/ui-egui/src/property_sheet/factor_slider.rs +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -6,20 +6,29 @@ use super::PropertySheet; use super::slider::{KNOB_RADIUS, kept_in}; use super::track::Track; +/// Decimal places in the displayed factor +const FACTOR_DECIMALS: usize = 2; + impl PropertySheet<'_> { /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> Option { let (control, center_y) = self.row(label); let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; let track_range = -doublings..=doublings; let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); if dragged.is_some() { *factor = along.exp2(); } - let shown = format!("×{:.2}", *factor); - let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + + let format_factor = |factor: f32| format!("×{factor:.FACTOR_DECIMALS$}"); + self.measure_track_values(&track_range, |end| format_factor(end.exp2())); + let shown = format_factor(*factor); + + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, FACTOR_DECIMALS); Self::apply_typed(factor, entered, dragged) } } diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 59a00a04..f93f3f0f 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -43,6 +43,7 @@ mod section_tabs; #[path = "property_sheet.rs"] mod sheet; mod sheet_measure; +mod sheet_measurements; mod size_columns; mod size_columns_response; mod slider; @@ -123,6 +124,9 @@ const LOOSE_LABEL_AIR: f32 = 2.0; /// The narrowest value column at a slider's right end const VALUE_MIN_WIDTH: f32 = 26.0; +/// The most the value column reserves for values not on show yet, so a huge range leaves the tracks their length +const TRACK_VALUE_RESERVE_MAX: f32 = 72.0; + /// Air between a slider track's end and the value column, room for the knob and a gap const TRACK_TO_VALUE: f32 = 14.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index e1e5b1b6..3ad52b78 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -1,13 +1,13 @@ +use std::ops::RangeInclusive; + use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; use super::{ - CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, VALUE_MIN_WIDTH, open_card::OpenCard, section_tabs, - sheet_measure::SheetMeasure, + CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, TRACK_VALUE_RESERVE_MAX, VALUE_MIN_WIDTH, + open_card::OpenCard, section_tabs, sheet_measure::SheetMeasure, sheet_measurements::SheetMeasurements, }; use crate::theme::{Tokens, semibold}; -type SheetMeasures = egui::cache::FramePublisher; - /// The Properties panel being laid out this frame: where the controls column is, which card is open, and what this frame measured for the next one pub(crate) struct PropertySheet<'u> { pub(crate) ui: &'u mut Ui, @@ -29,15 +29,22 @@ pub(crate) struct PropertySheet<'u> { pub(super) held: bool, /// Sub-headers so far in the current folding section: a later one takes air above it pub(super) sub_headers: usize, + + /// The value font's widest digit, found on first use + pub(super) widest_digit: Option, } impl<'u> PropertySheet<'u> { /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); - let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); + let viewport = ui.ctx().viewport_id(); + let measurements = ui.ctx().plugin_or_default::(); + let used = measurements.lock().get(viewport, id).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { tokens: Tokens::get(ui.ctx()), id, @@ -56,8 +63,10 @@ impl<'u> PropertySheet<'u> { info: None, held: false, sub_headers: 0, + widest_digit: None, ui, }; + let result = body(&mut sheet); sheet.close_card(); if !sheet.sections.is_empty() { @@ -65,9 +74,15 @@ impl<'u> PropertySheet<'u> { section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); } + let mut seen = sheet.seen; + + // Keep the previous width while a pointer may be dragging a track + if sheet.ui.input(|input| input.pointer.any_down()) { + seen.value_width = seen.value_width.max(used.value_width); + } + // Refresh visible sheets so measurements of closed sheets expire - let seen = sheet.seen; - sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); + measurements.lock().set(viewport, id, seen); if seen != used { sheet.ui.ctx().request_discard("Properties columns changed"); } @@ -91,6 +106,36 @@ impl<'u> PropertySheet<'u> { self.seen.value_width = self.seen.value_width.max(width); } + /// Reserves room for the track's formatted values, up to the limit for unseen values. + pub(super) fn measure_track_values(&mut self, range: &RangeInclusive, format_value: impl Fn(f32) -> String) { + let widest_digit = self.widest_digit(); + let [start, end] = [*range.start(), *range.end()] + .map(|limit| format_value(limit).chars().map(|character| if character.is_ascii_digit() { widest_digit } else { character }).collect::()); + + let distinct_end = (end != start).then_some(end); + let painter = self.ui.painter(); + for shown in std::iter::once(start).chain(distinct_end) { + let width = painter.layout_no_wrap(shown, semibold(TEXT_SIZE), Color32::WHITE).size().x.min(TRACK_VALUE_RESERVE_MAX); + self.seen.value_width = self.seen.value_width.max(width); + } + } + + /// Digits differ in width, so a value between a track's ends can be wider than either end + fn widest_digit(&mut self) -> char { + if let Some(digit) = self.widest_digit { + return digit; + } + + let painter = self.ui.painter(); + let widest = ('0'..='9') + .map(|digit| (digit, painter.layout_no_wrap(digit.to_string(), semibold(TEXT_SIZE), Color32::WHITE).size().x)) + .max_by(|one, other| one.1.total_cmp(&other.1)) + .map_or('0', |(digit, _)| digit); + + self.widest_digit = Some(widest); + widest + } + pub(super) fn text_width(&self, text: &str, font: FontId) -> f32 { self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x } diff --git a/crates/ui-egui/src/property_sheet/sheet_measurements.rs b/crates/ui-egui/src/property_sheet/sheet_measurements.rs new file mode 100644 index 00000000..c04bdf49 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/sheet_measurements.rs @@ -0,0 +1,38 @@ +use egui::{ + Context, FullOutput, Id, Plugin, Ui, ViewportId, ViewportIdMap, + cache::{CacheTrait, FramePublisher}, +}; + +use super::sheet_measure::SheetMeasure; + +/// A sheet's previous measurements survive redraws of other native windows. +#[derive(Default)] +pub(super) struct SheetMeasurements { + by_viewport: ViewportIdMap>, +} + +impl SheetMeasurements { + pub(super) fn get(&self, viewport: ViewportId, sheet: Id) -> Option { + self.by_viewport.get(&viewport)?.get(&sheet).copied() + } + + pub(super) fn set(&mut self, viewport: ViewportId, sheet: Id, measure: SheetMeasure) { + self.by_viewport.entry(viewport).or_default().set(sheet, measure); + } +} + +impl Plugin for SheetMeasurements { + fn debug_name(&self) -> &'static str { + "Properties sheet measurements" + } + + fn on_end_pass(&mut self, ui: &mut Ui) { + if let Some(sheets) = self.by_viewport.get_mut(&ui.ctx().viewport_id()) { + sheets.evict_cache(); + } + } + + fn output_hook(&mut self, _context: &Context, output: &mut FullOutput) { + self.by_viewport.retain(|viewport, sheets| sheets.len() > 0 && output.viewport_output.contains_key(viewport)); + } +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 3697880b..644eefea 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -130,7 +130,10 @@ impl PropertySheet<'_> { self.paint_dial(pos2(dial_x, center_y), *degrees); - let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let format_angle = |angle: f32| if plus { format!("{angle:+.0}°") } else { format!("{angle:.0}°") }; + self.measure_track_values(&range, format_angle); + let shown = format_angle(*degrees); + let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } @@ -255,7 +258,7 @@ impl PropertySheet<'_> { edit } - /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + /// The value at the row's end of a track over `range`, answering as `label`'s value; a click turns it into a field, which returns the typed value when done #[allow(clippy::too_many_arguments)] pub(super) fn value_field( &mut self, @@ -267,11 +270,12 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.measure_track_values(range, |end| shown_value(end, decimals, suffix)); + let shown = shown_value(value, decimals, suffix); self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) } - /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it. A caller with a track measures its range first #[allow(clippy::too_many_arguments)] pub(super) fn column_value_field( &mut self, @@ -303,7 +307,7 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + let shown = shown_value(value, decimals, suffix); self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) } @@ -363,3 +367,10 @@ impl PropertySheet<'_> { pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { value.max(*range.start()).min(*range.end()) } + +/// `value` as a slider's end reads it +pub(super) fn shown_value(value: f32, decimals: usize, suffix: &str) -> String { + let mut shown = shown_number(value, decimals); + shown.push_str(suffix); + shown +} diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs index d7934290..6b961630 100644 --- a/crates/ui-egui/src/property_sheet/stacked_rows.rs +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -187,13 +187,14 @@ impl PropertySheet<'_> { info: None, held: self.held, sub_headers: self.sub_headers, + widest_digit: self.widest_digit, ui: &mut child, }; let result = body(&mut sheet); - let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, widest_digit, .. } = sheet; (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = (named, seen, card, air_at, drawn_bottom, empty, sections); - (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + (self.held, self.sub_headers, self.scope, self.band_scope, self.widest_digit) = (held, sub_headers, scope, band_scope, widest_digit); let bottom = child.min_rect().bottom().max(top); let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); @@ -305,6 +306,7 @@ impl PropertySheet<'_> { info: None, held: false, sub_headers: 0, + widest_digit: self.widest_digit, ui: &mut second_ui, }; let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 28b126c4..be383128 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -10,9 +10,11 @@ use texturecraft_engine::folder_cmds::next_seed; mod filtering; mod gallery; +mod slider_test_row; use filtering::Filtering; use gallery::Gallery; +use slider_test_row::SliderTestRow; /// Width of the Properties panel the mockups are drawn at const PANEL_WIDTH: f32 = 300.0; @@ -1017,6 +1019,74 @@ fn a_ramps_value_ends_on_the_linked_tiling_value() { assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); } +fn value_row_track(harness: &Harness<'_, (SliderTestRow, f32)>) -> Rect { + harness.get_by_role_and_label(egui::Role::Slider, "Value").rect() +} + +/// A value gaining a minus sign or digits moves no track (the value column followed the widest number on show) +#[test] +fn tracks_stay_put_as_their_values_gain_a_sign_and_digits() { + let rows = [ + (SliderTestRow::Signed, [0.0, -0.88, 0.88, -1.0]), + (SliderTestRow::RelativeAngle, [0.0, -88.0, 88.0, -180.0]), + (SliderTestRow::Factor, [1.0, 16.0, 0.1, 8.0]), + (SliderTestRow::Captioned, [0.0, -888.0, 888.0, -1000.0]), + ]; + + for (row, [first, rest @ ..]) in rows { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (row, first)); + harness.run_steps(3); + let before = value_row_track(&harness); + + for value in rest { + harness.state_mut().1 = value; + harness.run_steps(3); + assert_eq!(value_row_track(&harness), before, "the {row:?} track moved at {value}"); + } + } +} + +/// A range far past anything readable reserves only so much, and its track still ends in the panel's right half +#[test] +fn a_huge_range_leaves_its_track_its_length() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (SliderTestRow::HugeRange, 1.0)); + harness.run_steps(3); + + // An inverted track can still report a wide rectangle + let track = value_row_track(&harness); + assert!(track.right() > PANEL_WIDTH / 2.0, "the track ends at {}", track.right()); +} + +/// Dragging back from a value past the track's ends narrows the column only once the drag ends +#[test] +fn a_drag_from_a_typed_value_moves_no_track_until_release() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (SliderTestRow::Factor, 1000.0)); + harness.run_steps(3); + let before = value_row_track(&harness); + + harness.drag_at(before.center()); + + // Past egui's longest click, the press becomes a drag + harness.run_steps(5); + + assert!(harness.state().1 < 1000.0, "the press moved no value"); + assert_eq!(value_row_track(&harness), before, "the track moved under the drag"); + + // A detached panel redraws between two passes of the held slider + let viewport = egui::ViewportId::from_hash_of("floating panel"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + harness.ctx.run_ui(floating, |_| {}).textures_delta.clear(); + harness.step(); + + assert_eq!(value_row_track(&harness), before, "the floating window changed the held track"); + + harness.drop_at(before.center()); + harness.run_steps(3); + + assert!(value_row_track(&harness).right() > before.right(), "the column stayed wide after the release"); +} + #[test] fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { let context = egui::Context::default(); diff --git a/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs b/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs new file mode 100644 index 00000000..efb99f5b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs @@ -0,0 +1,41 @@ +use egui::{Color32, Ui}; + +use super::{PANEL_WIDTH, swatch}; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::Tokens; + +#[derive(Clone, Copy, Debug)] +pub(super) enum SliderTestRow { + Signed, + RelativeAngle, + Factor, + Captioned, + HugeRange, +} + +impl SliderTestRow { + /// Draws one slider in isolation so other rows cannot keep its value column wide. + pub(super) fn show(ui: &mut Ui, (row, value): &mut (Self, f32)) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "value row", |sheet| match row { + Self::Signed => { + sheet.signed_slider("Value", value, -1.0..=1.0, 2); + } + Self::RelativeAngle => { + sheet.relative_angle("Value", value, -180.0..=180.0); + } + Self::Factor => { + sheet.factor_slider("Value", value, 4.0, 0.0..=2000.0); + } + Self::Captioned => { + sheet.picture_sliders(&swatch(Color32::from_gray(128)), &mut [StackSlider::whole("Value", value, -1000.0..=1000.0)]); + } + Self::HugeRange => { + sheet.slider("Value", value, 0.0..=f32::MAX, 2); + } + }); + }); + } +} diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs new file mode 100644 index 00000000..5b735a38 --- /dev/null +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -0,0 +1,69 @@ +//! A failed autosave is announced in the interface. This is its own test binary because the data +//! folder it breaks is fixed once for the whole process. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use egui::accesskit::Live; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Removes the test's folder, also when an assertion fails +struct TempFolder(PathBuf); + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { + // Other loaders name the broken data folder too: only the autosave's own notice counts + harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() +} + +/// Run frames until `done`, giving the autosave worker real time to finish. +fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let started = Instant::now(); + while !done(harness) { + assert!(started.elapsed() < Duration::from_secs(60), "the autosave did not report"); + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn a_failing_autosave_is_announced_once_until_it_works_again() { + let folder = TempFolder(std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id()))); + std::fs::create_dir_all(&folder.0).unwrap(); + let root = folder.0.join("data"); + // A file where the data folder should be, so the autosave folder cannot be created + std::fs::write(&root, b"not a folder").unwrap(); + texturecraft_ui_egui::set_data_root(root.clone()); + + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + // Each frame is longer than the shortest autosave period, so every frame is due + let mut harness = Harness::builder() + .with_step_dt(61.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + // The notice is matched by its English text, whatever the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // One frame applies the language before any autosave reports + harness.step(); + harness.state_mut().ui.prefs.autosave_minutes = 1; + harness.state_mut().session.modified = true; + + run_until(&mut harness, |harness| notices(harness) > 0); + for _ in 0..20 { + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + let announced = harness.query_all_by_label_contains("Autosave to ").any(|node| node.accesskit_node().live() == Live::Polite); + assert!(announced, "the notice is a live region, so a screen reader reads it"); + + std::fs::remove_file(&root).unwrap(); + run_until(&mut harness, |harness| notices(harness) == 0); +}