diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index fea885a3a0..ac81fc5d47 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -22,6 +22,8 @@ next to them. | `assets/icons/history-brush.svg` | History Brush tool glyph: Lucide `brush` plus counter-clockwise history rewind arrow | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe | | `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) | +| `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) | +| `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 | | `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code | | `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) | | `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, (its colour schemes are LGPL-2.0-or-later) | Original work | diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 7e815db5d2..4c62f446ac 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -40,6 +40,16 @@ where T: Into, { let args: Vec = args.into_iter().map(Into::into).collect(); + // nightly-v1 is a desktop-only contract. Never let GUI profile arguments fall through + // to stable CLI/MCP directory and credential discovery. + if args.iter().take_while(|arg| arg.as_os_str() != std::ffi::OsStr::new("--")).any(|arg| { + let text = arg.to_string_lossy(); + text == "--launch-profile" || text == "--profile-root" || text.starts_with("--launch-profile=") || text.starts_with("--profile-root=") + }) { + let _ = writeln!(err, "nightly-v1 is supported only by the PhotoCraft desktop launcher protocol"); + return 2; + } + // Help and `--version` (`help`, `-h`, ` --help`, `-V`) come back as errors too, // for `out`, exit 0: the subcommand never runs. let cli = match parse(&args) { @@ -84,3 +94,14 @@ pub(crate) mod test_support { Invoke { code, stdout: String::from_utf8(stdout).unwrap(), stderr: String::from_utf8(stderr).unwrap() } } } + +#[cfg(test)] +mod nightly_protocol_tests { + #[test] + fn gui_profile_protocol_is_refused_before_any_cli_command() { + let result = super::test_support::invoke(&["--launch-profile", "nightly-v1", "--profile-root", "a-private-root", "--", "file.psd"]); + assert_eq!(result.code, 2); + assert!(result.stdout.is_empty()); + assert!(result.stderr.contains("desktop launcher protocol")); + } +} diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index f93f70752a..02445b1971 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -111,7 +111,7 @@ winit = { version = "=0.30.13", default-features = false, features = ["wayland-c [target.'cfg(target_os = "windows")'.dependencies] # Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal. xcap = "=0.9.8" -winsafe = { version = "=0.0.29", default-features = false, features = ["user"] } +winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] } [build-dependencies] diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 48ce637a52..0f5455057c 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -4,11 +4,42 @@ //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +#[path = "src/build_channel.rs"] +mod build_channel; + /// Embeds the Windows resources and delay-loads the print-only system DLLs (#5884, #8272). fn main() { println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_CHANNEL"); + println!("cargo:rustc-check-cfg=cfg(photocraft_nightly_v1)"); + let nightly = match std::env::var("PHOTOCRAFT_BUILD_CHANNEL").as_deref() { + Ok("nightly-v1") => { + println!("cargo:rustc-cfg=photocraft_nightly_v1"); + true + } + Ok("stable") | Err(std::env::VarError::NotPresent) => false, + _ => { + eprintln!("unsupported PHOTOCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); + std::process::exit(1); + } + }; println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); + println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION"); + let built_version = if nightly { + match std::env::var("PHOTOCRAFT_VERSION") { + Ok(version) if build_channel::is_nightly_version(&version) => version, + _ => { + eprintln!("nightly-v1 requires an explicit PHOTOCRAFT_VERSION feed identity"); + std::process::exit(1); + } + } + } else { + std::env::var("CARGO_PKG_VERSION").unwrap_or_default() + }; + println!("cargo:rustc-env=PHOTOCRAFT_BUILT_VERSION={built_version}"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } @@ -23,13 +54,17 @@ fn main() { println!("cargo:rustc-link-arg-bins=delayimp.lib"); } let mut res = winresource::WindowsResource::new(); - res.set_icon("../../assets/app-icon/photocraft.ico") - .set("ProductName", "PhotoCraft") - .set("FileDescription", "PhotoCraft image editor") + res.set_icon(build_channel::windows_icon_path(nightly)) + .set("ProductName", if nightly { "PhotoCraft Nightly" } else { "PhotoCraft" }) + .set("FileDescription", if nightly { "PhotoCraft Nightly image editor" } else { "PhotoCraft image editor" }) .set("CompanyName", "Learning Machines LLC") .set("LegalCopyright", "Copyright (c) the PhotoCraft authors. MIT OR Apache-2.0.") .set("OriginalFilename", "photocraft.exe") .set("InternalName", "photocraft"); + if nightly { + // Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion. + res.set("ProductVersion", &built_version); + } if let Err(e) = res.compile() { if std::env::var_os("PHOTOCRAFT_REQUIRE_WINRES").is_some() { panic!("embedding Windows resources failed: {e}"); diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index f1c20cfa6a..c70ef077ad 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -31,7 +31,10 @@ pub fn current() -> &'static DataDir { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { let exe = std::env::current_exe().ok(); - let d = resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)); + let d = match crate::launch_profile::current().root() { + Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override, warning: None }, + None => resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)), + }; if let Some(w) = &d.warning { log::warn!("{w}"); eprintln!("photocraft: {w}"); diff --git a/apps/photocraft/src/app_icon.rs b/apps/photocraft/src/app_icon.rs index 4fb8765e52..4dbe4f137d 100644 --- a/apps/photocraft/src/app_icon.rs +++ b/apps/photocraft/src/app_icon.rs @@ -1,6 +1,6 @@ //! The app icon, everywhere Windows, macOS and Linux show one (#248). //! -//! - **Executable:** `build.rs` embeds `assets/app-icon/photocraft.ico` (16–256 px) as icon +//! - **Executable:** `build.rs` selects the stable or nightly-only `.ico` (16–256 px) as icon //! resource 1, which Explorer, Alt+Tab and an unpinned taskbar button fall back to. //! - **Window:** [`window_icon`] sets the title-bar and taskbar icon at runtime (`WM_SETICON` on //! Windows, `_NET_WM_ICON` on X11, the Dock when running unbundled on macOS). @@ -9,15 +9,16 @@ //! shortcut's icon under its ``, so that id must carry the target's `.exe` extension //! (ICE50); an extensionless id showed a blank page on the taskbar. The tests below check it. //! -//! The process keeps Windows' implicit AppUserModelID (derived from the executable path), which -//! is what makes that matching work for both the MSI shortcut and the portable exe. An explicit -//! ID would need a Win32 call (`unsafe`, which the workspace forbids) and would then also have to -//! be stamped on the shortcut, or the taskbar would stop matching the two. +//! Stable keeps Windows' implicit AppUserModelID (derived from the executable path), which +//! is what makes that matching work for both the MSI shortcut and the portable exe. Changing +//! stable's ID would also require changing its matching shortcut policy. Nightly is separate: +//! its app bootstrap uses the existing safe Windows bindings to set its persistent channel +//! identity before any native window. /// Window, taskbar and (when running unbundled) Dock icon. macOS gets the padded 1024 px render /// on Apple's icon grid; elsewhere the 256 px hicolor render of the full tile. pub fn window_icon() -> egui::IconData { - match eframe::icon_data::from_png_bytes(PNG) { + match eframe::icon_data::from_png_bytes(icon_png(crate::build_flavor::COMPILED, cfg!(target_os = "macos"))) { Ok(icon) => icon, Err(e) => { log::warn!("app icon: {e}"); @@ -26,6 +27,16 @@ pub fn window_icon() -> egui::IconData { } } +fn icon_png(flavor: crate::build_flavor::BuildFlavor, macos: bool) -> &'static [u8] { + if flavor != crate::build_flavor::BuildFlavor::NightlyV1 { + PNG + } else if macos { + include_bytes!("../../../assets/app-icon/photocraft-nightly-1024.png") + } else { + include_bytes!("../../../assets/app-icon/photocraft-nightly.png") + } +} + /// Whether the window gets [`window_icon`] at runtime: everywhere except inside a macOS app /// bundle. There the Dock shows the bundle's `PhotoCraft.icns` (`CFBundleIconFile`), which macOS /// renders in its own style (Liquid Glass and its tinted and dark variants); a runtime PNG @@ -60,6 +71,41 @@ const PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps #[cfg(test)] mod tests { use super::*; + #[test] + fn nightly_uses_each_platforms_distinct_nonblank_native_size_icon() { + use crate::build_flavor::BuildFlavor; + assert_eq!(icon_png(BuildFlavor::Stable, true), PNG); + assert_eq!(icon_png(BuildFlavor::Stable, false), PNG); + for (macos, expected_size) in [(false, 256), (true, 1024)] { + let nightly = icon_png(BuildFlavor::NightlyV1, macos); + assert_ne!(nightly, PNG); + let icon = eframe::icon_data::from_png_bytes(nightly).unwrap(); + assert_eq!((icon.width, icon.height), (expected_size, expected_size)); + assert!(icon.rgba.chunks(4).any(|pixel| pixel[3] > 0)); + } + } + + #[test] + fn nightly_executable_icon_retains_all_six_shell_sizes() { + let ico = include_bytes!("../../../assets/app-icon/photocraft-nightly.ico"); + assert_ne!(ico.as_slice(), ICO); + assert_eq!((u16_at(ico, 0), u16_at(ico, 2)), (0, 1)); + let mut sizes = Vec::new(); + for i in 0..u16_at(ico, 4) { + let entry = 6 + 16 * i; + let width = if ico[entry] == 0 { 256 } else { usize::from(ico[entry]) }; + let height = if ico[entry + 1] == 0 { 256 } else { usize::from(ico[entry + 1]) }; + assert_eq!(width, height); + let image = &ico[u32_at(ico, entry + 12)..][..u32_at(ico, entry + 8)]; + assert!(image.starts_with(b"\x89PNG\r\n\x1a\n")); + let decoded = eframe::icon_data::from_png_bytes(image).unwrap(); + assert_eq!((decoded.width as usize, decoded.height as usize), (width, height)); + sizes.push(width); + } + for expected in [16, 24, 32, 48, 64, 256] { + assert!(sizes.contains(&expected), "missing nightly icon size {expected}"); + } + } const ICO: &[u8] = include_bytes!("../../../assets/app-icon/photocraft.ico"); const WXS: &str = include_str!("../../../packaging/windows/photocraft.wxs"); diff --git a/apps/photocraft/src/build_channel.rs b/apps/photocraft/src/build_channel.rs new file mode 100644 index 0000000000..8d0457f43e --- /dev/null +++ b/apps/photocraft/src/build_channel.rs @@ -0,0 +1,53 @@ +//! The build-time nightly identity shared by the build script and its pure regression tests. +pub fn is_nightly_version(version: &str) -> bool { + let Some((base, suffix)) = version.split_once("-nightly.") else { return false }; + let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); + let base: Vec<_> = base.split('.').collect(); + let parts: Vec<_> = suffix.split('.').collect(); + base.len() == 3 + && base.iter().all(|s| digits(s)) + && parts.len() == 4 + && parts[0].len() == 8 + && digits(parts[0]) + && digits(parts[1]) + && digits(parts[2]) + && parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) +} +pub fn windows_icon_path(nightly: bool) -> &'static str { + if nightly { "../../assets/app-icon/photocraft-nightly.ico" } else { "../../assets/app-icon/photocraft.ico" } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() { + assert_eq!(windows_icon_path(false), "../../assets/app-icon/photocraft.ico"); + assert_eq!(windows_icon_path(true), "../../assets/app-icon/photocraft-nightly.ico"); + } + + #[test] + fn explicit_feed_identity_is_required_for_a_nightly_build() { + assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345")); + for invalid in [ + "", + "0.23.1", + "0.23.1-nightly", + "0.23.1-nightly.20261120", + "0.23.1-nightly.20261120.17.1.gABCDEF012345", + "0.23.1-nightly.20261120.17.1.gabcdef012345\n", + ] { + assert!(!is_nightly_version(invalid), "{invalid:?}"); + } + } + #[test] + fn version_cannot_inject_a_path_or_an_extra_build_directive() { + for invalid in [ + "../0.23.1-nightly.20261120.1.1.gabcdef012345", + "0.23.1-nightly.20261120.1.1.gabcdef012345/other", + "0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other", + ] { + assert!(!is_nightly_version(invalid)); + } + } +} diff --git a/apps/photocraft/src/build_flavor.rs b/apps/photocraft/src/build_flavor.rs new file mode 100644 index 0000000000..b14e633370 --- /dev/null +++ b/apps/photocraft/src/build_flavor.rs @@ -0,0 +1,70 @@ +//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build. +use crate::launch_profile::Profile; +use std::ffi::OsString; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + Stable, + NightlyV1, +} + +pub const COMPILED: BuildFlavor = if cfg!(photocraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; + +pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { + match (flavor, profile.is_nightly()) { + (BuildFlavor::NightlyV1, false) => Err("Open PhotoCraft Nightly from ArtCraft Launcher".into()), + (BuildFlavor::Stable, true) => Err("This is a stable PhotoCraft build; nightly-v1 requires the nightly build".into()), + _ => Ok(()), + } +} + +pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { + desktop_session && flavor == BuildFlavor::NightlyV1 +} + +pub fn version_query(args: &[OsString]) -> bool { + matches!(args, [arg] if arg == "--version" || arg == "-V") +} + +pub fn version(flavor: BuildFlavor, stable: &str) -> String { + match flavor { + BuildFlavor::Stable => stable.to_owned(), + BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_a_nightly_desktop_refusal_requests_a_native_dialog() { + assert!(needs_native_error(BuildFlavor::NightlyV1, true)); + assert!(!needs_native_error(BuildFlavor::NightlyV1, false)); + assert!(!needs_native_error(BuildFlavor::Stable, true)); + assert!(!needs_native_error(BuildFlavor::Stable, false)); + } + + #[test] + fn nightly_build_without_a_profile_is_refused_before_startup() { + let started = std::cell::Cell::new(false); + let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); + assert!(result.unwrap_err().contains("ArtCraft Launcher")); + assert!(!started.get()); + } + #[test] + fn stable_and_nightly_flavors_accept_only_their_own_profile() { + let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); + assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); + assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); + assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); + } + #[test] + fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() { + assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1"); + assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)"); + assert!(version_query(&["--version".into()])); + assert!(version_query(&["-V".into()])); + assert!(!version_query(&["--".into(), "--version".into()])); + assert!(!version_query(&[])); + } +} diff --git a/apps/photocraft/src/launch_profile.rs b/apps/photocraft/src/launch_profile.rs new file mode 100644 index 0000000000..f8bfa12717 --- /dev/null +++ b/apps/photocraft/src/launch_profile.rs @@ -0,0 +1,170 @@ +//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state. +//! Stable launches retain their original arguments and directory policy. No environment mutation. + +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 fn current() -> &'static Profile { + PROFILE.get().unwrap_or(&Profile::Stable) +} + +pub fn install(profile: Profile) -> Result<(), String> { + PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) +} + +/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is +/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here. +pub fn parse(args: Vec) -> 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()), + } +} + +/// Validation finishes before the caller's first startup effect. Stable never calls the nightly +/// root validator, so its old portable/config 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, photocraft_automation::app_dirs::ensure_writable) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + fn args(values: &[&str]) -> Vec { + values.iter().map(OsString::from).collect() + } + fn absolute() -> &'static str { + if cfg!(windows) { r"C:\NightlyData\profiles\photocraft" } else { "/nightly-data/profiles/photocraft" } + } + fn nightly() -> Vec { + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) + } + + #[test] + fn stable_arguments_and_directory_policy_are_unchanged() { + for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] { + let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); + assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + } + } + + #[test] + fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { + let mut argv = nightly(); + argv.extend(args(&["--profile-root", "image with spaces.psd"])); + let launch = parse(argv).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); + assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"])); + } + + #[test] + fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + for argv in [ + args(&["--launch-profile", VERSION]), + args(&["--profile-root", absolute()]), + args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]), + args(&["--launch-profile", VERSION, "--profile-root", absolute()]), + ] { + assert!(parse(argv).is_err()); + } + } + + #[test] + fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { + let reached = Cell::new(false); + let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); + assert!(result.is_err()); + assert!(!reached.get()); + } + + #[test] + fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { + let checked = PathBuf::from(absolute()).join("checked"); + let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); + assert_eq!(launch.profile.root(), Some(checked.as_path())); + assert!(launch.profile.is_nightly()); + } +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 38ff2c94ad..c82529ce89 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -33,13 +33,19 @@ mod app_dirs; mod app_icon; #[cfg(target_os = "macos")] mod apple_events; +#[cfg(test)] +mod build_channel; +mod build_flavor; mod caps_lock; mod crash_guard; mod cursor; mod gpu_startup; mod launch_args; +mod launch_profile; #[cfg(target_os = "macos")] mod mac_window; +mod process_identity; +mod profile_root; // Pure logic is tested on every platform; only Linux runs the check. #[cfg(not(target_arch = "wasm32"))] mod external_svg; @@ -67,7 +73,7 @@ use photocraft_ui_egui::PhotocraftApp; use photocraft_ui_egui::Prefix; use photocraft_ui_egui::window_policy::{self, Backend, Frame, TitleBarPref}; -use photocraft_ui_egui::os_window::APP_ID; +use photocraft_ui_egui::os_window; /// The smallest the main window may be, in points. const MIN_WINDOW_SIZE: [f32; 2] = [760.0, 480.0]; @@ -161,8 +167,12 @@ fn control_port_for(cli: Option, prefs: &photocraft_engine::prefs::Integrat /// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves. fn native_options(frame: &Frame) -> eframe::NativeOptions { let viewport = egui::ViewportBuilder::default().with_icon(app_icon::viewport_icon(std::env::current_exe().ok().as_deref())); - let viewport = - viewport.with_app_id(APP_ID).with_title("PhotoCraft").with_inner_size([1440.0, 900.0]).with_min_inner_size(MIN_WINDOW_SIZE).with_drag_and_drop(true); + let viewport = viewport + .with_app_id(os_window::app_id()) + .with_title(os_window::name_for(os_window::identity())) + .with_inner_size([1440.0, 900.0]) + .with_min_inner_size(MIN_WINDOW_SIZE) + .with_drag_and_drop(true); eframe::NativeOptions { viewport: window_policy::apply(viewport, frame), centered: true, @@ -225,18 +235,19 @@ fn claim_single_instance( mut launch_options: Vec, ) -> std::ops::ControlFlow<(), Option> { use std::ops::ControlFlow::{Break, Continue}; - let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok(); + let nightly = launch_profile::current().is_nightly(); + let new_instance_env = if nightly { None } else { std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok() }; // A variable documented as the equivalent of a per-launch flag counts as that flag: a // launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it // keeps its own process instead of handing its files over and being ignored. launch_options.extend_from_slice(&single_instance::env_launch_options()); let context = single_instance::LaunchContext { - per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform, - new_instance_flag: new_instance, + per_user_settings: launch_profile::current().is_nightly() || app_dirs::current().mode == app_dirs::Mode::Platform, + new_instance_flag: new_instance && !nightly, new_instance_env: new_instance_env.as_deref(), - control, + control: control && !nightly, unreadable_paths, - launch_options: &launch_options, + launch_options: if nightly { &[] } else { &launch_options }, }; match (single_instance::skip_reason(&context), services::config_dir()) { (Some(reason), _) => { @@ -388,7 +399,57 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup } } +fn initialize_nightly_process_identity() -> Result<(), String> { + process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(os_window::LaunchIdentity::NightlyV1)) +} + +fn report_launch_profile_error(error: &str) { + eprintln!("PhotoCraft launch profile: {error}"); + let desktop_session = cfg!(windows) + || cfg!(target_os = "macos") + || (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty()))); + if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) { + if let Err(error) = initialize_nightly_process_identity() { + eprintln!("PhotoCraft launch profile: {error}"); + return; + } + #[cfg(any(windows, target_os = "linux", target_os = "macos"))] + let _ = rfd::MessageDialog::new() + .set_title("PhotoCraft Nightly") + .set_description(error) + .set_level(rfd::MessageLevel::Error) + .set_buttons(rfd::MessageButtons::Ok) + .show(); + } +} + fn main() -> eframe::Result { + // The trusted Launcher protocol is decided before logger/crash/update/font/prefs access. + let argv: Vec<_> = std::env::args_os().skip(1).collect(); + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "PhotoCraft {}", build_flavor::version(build_flavor::COMPILED, env!("PHOTOCRAFT_BUILT_VERSION"))); + return Ok(()); + } + let early = launch_profile::parse(argv) + .and_then(|launch| { + build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; + initialize_nightly_process_identity()?; + 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() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable }; + if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + report_launch_profile_error(&error); + std::process::exit(2); + } + // Before anything starts a thread: may re-execute this process with glibc tuned to return // the memory of closed documents (#8743). photocraft_engine::malloc_tuning::apply(); @@ -396,7 +457,9 @@ fn main() -> eframe::Result { let logger = logging::install(); crash_guard::install_hook(); #[cfg(not(target_arch = "wasm32"))] - if let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { + if !launch_profile::current().is_nightly() + && let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) + { if let Err(e) = done { eprintln!("PhotoCraft update helper failed: {e}"); std::process::exit(1); @@ -410,7 +473,7 @@ fn main() -> eframe::Result { // option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT: issues #701, #6429, #6431) // names the argument on standard error and exits 2, so a launcher sees the failure. Neither // panics when the stream is closed or a pipe (`photocraft --help | head -1`). - let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit()); + let launch = launch_args::parse(launch_args::command(), early.args).unwrap_or_else(|e| e.exit()); let launch_args::FileNames { openable: files, unreadable: unreadable_paths } = launch.file_names(); let launch_args::LaunchArgs { files: _, @@ -451,7 +514,12 @@ fn main() -> eframe::Result { let _ = (new_instance, &launch_options); // Bind and authenticate the authorized control listener before display/GPU initialization. - let ControlSetup { control, warning: control_warning } = control_setup(&prefs.integrations, control_port, auth, &automation); + let ControlSetup { control, warning: control_warning } = if launch_profile::current().is_nightly() { + // No inherited stable token file/Launcher agent switch is consulted by this first protocol. + ControlSetup { control: None, warning: None } + } else { + control_setup(&prefs.integrations, control_port, auth, &automation) + }; #[cfg(target_os = "linux")] let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok()); @@ -550,7 +618,7 @@ fn main() -> eframe::Result { let created_in_callback = app_created.clone(); let started_sentinel = sentinel.clone(); let result = eframe::run_native( - "PhotoCraft", + os_window::name_for(os_window::identity()), options, Box::new(move |cc| { created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed); @@ -681,21 +749,24 @@ fn main() -> eframe::Result { // switch (Settings › AI agents) is the one consent; without it, as before, a Control // Port saved in the preferences. The launch flags (`--control`) manage the connection // for the whole run instead. - app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, { - let ctx = cc.egui_ctx.clone(); - move || ctx.request_repaint() - })); - let link = if let Some((listener, token, _)) = control { - let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx); - let (requests, server) = craft::automation::server::serve(listener, token, host)?; - eprintln!("photocraft: control server listening on {}", server.addr); - app = app.with_control(requests); - craft::automation::agents::AgentLink::from_launch(server) - } else { - app.services.agent_automation = Some(Box::new(services::agent_automation)); - craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version()) - }; - app.services.agent_link = Some(link); + if !launch_profile::current().is_nightly() { + app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, { + let ctx = cc.egui_ctx.clone(); + move || ctx.request_repaint() + })); + let link = if let Some((listener, token, _)) = control { + let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx); + let (requests, server) = craft::automation::server::serve(listener, token, host)?; + eprintln!("photocraft: control server listening on {}", server.addr); + app = app.with_control(requests); + craft::automation::agents::AgentLink::from_launch(server) + } else { + app.services.agent_automation = Some(Box::new(services::agent_automation)); + craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version()) + }; + app.services.agent_link = Some(link); + } + #[cfg(target_os = "macos")] { app.services.os_events = Some(apple_events.connect(&cc.egui_ctx)); @@ -1173,7 +1244,7 @@ mod tests { fn the_desktop_entry_names_the_window_class() { let entry = include_str!("../../../packaging/linux/ai.storyteller.photocraft.desktop"); let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass=")); - assert_eq!(class, Some(super::APP_ID)); + assert_eq!(class, Some(super::os_window::APP_ID)); } /// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and diff --git a/apps/photocraft/src/process_identity.rs b/apps/photocraft/src/process_identity.rs new file mode 100644 index 0000000000..2c26439067 --- /dev/null +++ b/apps/photocraft/src/process_identity.rs @@ -0,0 +1,62 @@ +//! Set the immutable nightly Windows identity before any native window or COM service. +//! Stable deliberately leaves its implicit shortcut/path identity unchanged. + +use std::sync::OnceLock; + +pub fn initialize(nightly: bool, app_id: &str) -> Result<(), String> { + configure(nightly && cfg!(windows), app_id, |id| { + static RESULT: OnceLock> = OnceLock::new(); + RESULT + .get_or_init(|| { + #[cfg(windows)] + { + winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?; + let actual = winsafe::GetCurrentProcessExplicitAppUserModelID() + .map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?; + if actual != id { + return Err("the native Windows identity did not match the selected nightly channel".into()); + } + Ok(()) + } + #[cfg(not(windows))] + { + let _ = id; + Ok(()) + } + }) + .clone() + }) +} + +fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> { + if explicit_nightly { set(app_id) } else { Ok(()) } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stable_does_not_call_the_explicit_identity_api() { + configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap(); + } + + #[test] + fn nightly_applies_the_supplied_identity_once() { + let calls = std::cell::Cell::new(0); + configure(true, "nightly-id", |id| { + assert_eq!(id, "nightly-id"); + calls.set(calls.get() + 1); + Ok(()) + }) + .unwrap(); + assert_eq!(calls.get(), 1); + } + + #[test] + fn native_identity_failure_is_returned_instead_of_starting_a_window() { + let started = std::cell::Cell::new(false); + let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true)); + assert_eq!(result.unwrap_err(), "native identity refused"); + assert!(!started.get()); + } +} diff --git a/apps/photocraft/src/profile_root.rs b/apps/photocraft/src/profile_root.rs new file mode 100644 index 0000000000..ca80532ce3 --- /dev/null +++ b/apps/photocraft/src/profile_root.rs @@ -0,0 +1,371 @@ +//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. + +use std::ffi::OsString; +use std::path::{Component, Path, PathBuf}; + +#[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 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) +} + +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) +} + +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 install, 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()) +} + +fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { + let mut roots = match platform { + Platform::Windows => { + ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("Photocraft"))).collect::, _>>()? + } + Platform::Linux => { + 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("photocraft"))) + .collect::, _>>()?; + roots.extend(["/usr/bin/photocraft", "/usr/local/bin/photocraft", "/opt/photocraft"].map(PathBuf::from)); + roots + } + Platform::Mac => { + let home = required_base(env, "HOME")?; + let library = home.join("Library"); + vec![ + library.join("Application Support/Photocraft"), + library.join("Caches/Photocraft"), + library.join("Caches/ai.storyteller.photocraft"), + library.join("Preferences/Photocraft"), + library.join("Preferences/ai.storyteller.photocraft.plist"), + library.join("Saved Application State/ai.storyteller.photocraft.savedState"), + home.join("Applications/PhotoCraft.app"), + PathBuf::from("/Applications/PhotoCraft.app"), + ] + } + }; + roots.push(installation_boundary(platform, exe)?); + roots.into_iter().map(|p| canonical_future(&p)).collect() +} + +/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem +/// boundary tests exercise the real policy without starting the app or changing global state. +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) +} + +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")?; + if env("PHOTOCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) { + return Err("nightly-v1 cannot be combined with PHOTOCRAFT_CONFIG_DIR".into()); + } + if platform != Platform::Windows && env("FLATPAK_ID").is_some_and(|v| !v.is_empty()) { + // These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its + // runtime socket namespace could point another profile at the stable app's socket. + return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into()); + } + let chosen = canonical_future(root)?; + let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; + let forbidden = forbidden_roots(platform, &env, &exe)?; + if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { + return Err("the nightly root must not overlap stable data or an installation".into()); + } + let mut create = std::fs::DirBuilder::new(); + create.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt as _; + create.mode(0o700); + } + create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; + let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; + if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { + return Err("the nightly profile changed while it was being validated".into()); + } + writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; + Ok(confirmed) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct Fixture { + root: PathBuf, + env: BTreeMap, + exe: PathBuf, + } + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let root = loop { + let candidate = std::env::temp_dir().join(format!("photocraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + match std::fs::create_dir(&candidate) { + Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create owned fixture: {error}"), + } + }; + let home = root.join("home"); + let exe = root.join("install/photocraft"); + 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), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] + .into_iter() + .map(|(key, value)| (key.into(), value.into_os_string())) + .collect(); + Self { root, env, exe } + } + + fn get(&self, key: &str) -> Option { + self.env.get(key).cloned() + } + + fn check(&self, platform: Platform, root: &Path) -> Result { + validate_for( + platform, + root, + |key| self.get(key), + Some(&self.exe), + |dir| { + let probe = dir.join("exclusive-test-probe"); + let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + drop(file); + std::fs::remove_file(probe) + }, + ) + } + + fn home(&self) -> PathBuf { + PathBuf::from(self.get("HOME").unwrap()) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Only the directory successfully created by this fixture is owned for removal. + std::fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() { + let fixture = Fixture::new(); + let root = fixture.home().join("nightly/profiles/photocraft"); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + assert!(overlaps(&root, &root.join("Recovery"), platform)); + assert!(overlaps(&root.join("Recovery"), &root, platform)); + assert!(!overlaps(&root, &root.with_file_name("photocraft-other"), platform)); + } + } + + #[test] + fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() { + let mut fixture = Fixture::new(); + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + fixture.env.insert(key.into(), fixture.root.join(key).into_os_string()); + } + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("photocraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap(); + for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes"); + } + let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap()); + let nightly = data.join("ArtCraftLauncher/nightly/profiles/photocraft"); + assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly); + assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0); + } + + #[test] + fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() { + let mut fixture = Fixture::new(); + fixture.exe = fixture.root.join("install/PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft"); + std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap(); + std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap(); + let library = fixture.home().join("Library"); + for suffix in [ + "Application Support/Photocraft", + "Caches/Photocraft", + "Caches/ai.storyteller.photocraft", + "Preferences/Photocraft", + "Saved Application State/ai.storyteller.photocraft.savedState", + ] { + let stable = library.join(suffix); + assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile"); + assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap")); + assert!(!inside_resources.exists()); + let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/photocraft"); + assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid); + } + + #[test] + fn windows_roaming_local_and_install_fences_remain_active() { + let fixture = Fixture::new(); + for key in ["APPDATA", "LOCALAPPDATA"] { + let stable = PathBuf::from(fixture.get(key).unwrap()).join("Photocraft"); + assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap")); + assert!(!stable.exists()); + } + assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err()); + assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/photocraft")).is_ok()); + } + + #[test] + fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { + let mut fixture = Fixture::new(); + let candidate = fixture.home().join("nightly/profiles/photocraft"); + fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute")); + fixture.env.remove("XDG_CACHE_HOME"); + fixture.env.insert("PHOTOCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("PHOTOCRAFT_CONFIG_DIR")); + fixture.env.remove("PHOTOCRAFT_CONFIG_DIR"); + fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.photocraft".into()); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak")); + fixture.env.remove("FLATPAK_ID"); + fixture.env.remove("HOME"); + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME")); + assert!(!candidate.exists()); + } + + #[test] + fn non_directory_and_failed_write_probe_never_fall_back_to_stable() { + let fixture = Fixture::new(); + let file = fixture.home().join("not-a-directory"); + std::fs::write(&file, b"do not replace me").unwrap(); + assert!(fixture.check(Platform::Linux, &file).is_err()); + assert_eq!(std::fs::read(file).unwrap(), b"do not replace me"); + let candidate = fixture.home().join("nightly"); + let calls = std::cell::Cell::new(0); + let result = validate_for( + Platform::Linux, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + |_| { + calls.set(calls.get() + 1); + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal")) + }, + ); + assert!(result.unwrap_err().contains("not writable")); + assert_eq!(calls.get(), 1); + assert!(!fixture.home().join(".config/photocraft").exists()); + } + + #[cfg(unix)] + #[test] + fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() { + use std::os::unix::fs::symlink; + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/photocraft"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("sentinel"), b"untouched").unwrap(); + let alias = fixture.home().join("alias"); + symlink(&stable, &alias).unwrap(); + assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap")); + let missing = fixture.home().join("missing-target"); + let dangling = fixture.home().join("dangling"); + symlink(&missing, &dangling).unwrap(); + assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err()); + assert!(!missing.exists()); + assert!(!stable.join("nightly").exists()); + assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched"); + } +} diff --git a/assets/app-icon/README.md b/assets/app-icon/README.md index b229aadee4..66c6370b68 100644 --- a/assets/app-icon/README.md +++ b/assets/app-icon/README.md @@ -44,3 +44,15 @@ details and tests the `.ico` sizes and the WiX icon references. Replace `photocraft.svg` (and `photocraft-small.svg`), then run `packaging/icons.sh`. It needs `resvg`, plus `iconutil` on macOS; the `.ico` is packed by `cargo xtask ico`. + +## Nightly channel + +The nightly derivatives keep the foreground artwork, alpha and Mac padding unchanged. Only the +background contribution changes from the stable blue to the selected deep background. There is +no letter badge or crescent; the app and Launcher also identify the channel in text. + +`photocraft-nightly.png` and its nine-frame ICO use the existing own256 master. The separate +`photocraft-nightly-1024.png` and eleven-slot ICNS use the actual padded Mac1024 master, not an +upscale. Input/output hashes, the palette-fit recipe and container sizes are recorded in +[`nightly-provenance.json`](nightly-provenance.json). Stable source files are not recoloured. +The old N-marked private Windows isolation package is separate and is not rebuilt for this art. diff --git a/assets/app-icon/nightly-provenance.json b/assets/app-icon/nightly-provenance.json new file mode 100644 index 0000000000..d44682abe0 --- /dev/null +++ b/assets/app-icon/nightly-provenance.json @@ -0,0 +1,60 @@ +{ + "title": "PhotoCraft nightly deep-background icons", + "author": "@skylartaylor", + "license": "MIT OR Apache-2.0", + "source_commit": "06afefff534fb18ca7ea2725a9f476fe477dbd29", + "inputs": [ + { + "path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png", + "sha256": "efd02e0b8ea76c59fbc3a9692ddc21faae6064cc9f9492898df1facec3b5b57d", + "purpose": "Windows/Linux native256 master" + }, + { + "path": "assets/app-icon/photocraft-1024.png", + "sha256": "00a39c5ccbcb2b5f144573b1cedb6c387c4416ad06fd1cf2865b0737458ee704", + "purpose": "native padded Mac1024 master; not upscaled from256" + } + ], + "method": { + "kind": "original code-generated derivative of the project-owned icon", + "original_palette": { + "ink": "#0b0b0c", + "paper": "#efe9dc", + "background": "#2f7bf5" + }, + "nightly_background": "#22395d", + "transform": "Fit background contribution in the existing ink/paper/background palette and change only that contribution. Preserve alpha/padding and neutral foreground/detail RGBA. Derive native-size frames separately from their corresponding unchanged-resolution masters and pack PNG frames into ICO/ICNS. No crescent, letter or badge.", + "generator_sha256": "a04dcbba501985de729d37d352597de6ffb2ad993f1596eced6b12bffc114d85" + }, + "outputs": { + "assets/app-icon/photocraft-nightly.png": "7a79aff027f9f95cef0edc0a84ce3791af302b6351ebca4d0e736477e3b3f031", + "assets/app-icon/photocraft-nightly.ico": "87f67bc7b9ce18f54ab62769d7e6849d9ed0fd2658fce7db1a1eb05140fad2f4", + "assets/app-icon/photocraft-nightly-1024.png": "8de1e42f70720c7b8c66f40f443e7f7a423690cfcb062725d2e563c5f8fd51b1", + "assets/app-icon/photocraft-nightly.icns": "9ceecf811014509cc1444f44aaa0d31715a1e2439e943aec77c510dd4b2bf8f0" + }, + "ico_frame_sizes": [ + 16, + 20, + 24, + 32, + 40, + 48, + 64, + 128, + 256 + ], + "icns_png_slots": { + "icp4": 16, + "icp5": 32, + "ic11": 32, + "icp6": 64, + "ic12": 64, + "ic07": 128, + "ic08": 256, + "ic13": 256, + "ic09": 512, + "ic14": 512, + "ic10": 1024 + }, + "validation": "Source/input/output hashes, PNG CRC/dimensions and exact container members checked; supplied generator pixel proof preserves foreground/alpha. Visual comparison reviewed. Native Explorer/Finder/iconutil/app-package qualification remains unrun." +} diff --git a/assets/app-icon/photocraft-nightly-1024.png b/assets/app-icon/photocraft-nightly-1024.png new file mode 100644 index 0000000000..7d061a7f95 Binary files /dev/null and b/assets/app-icon/photocraft-nightly-1024.png differ diff --git a/assets/app-icon/photocraft-nightly.icns b/assets/app-icon/photocraft-nightly.icns new file mode 100644 index 0000000000..4e567c14a0 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.icns differ diff --git a/assets/app-icon/photocraft-nightly.ico b/assets/app-icon/photocraft-nightly.ico new file mode 100644 index 0000000000..cb81b19133 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.ico differ diff --git a/assets/app-icon/photocraft-nightly.png b/assets/app-icon/photocraft-nightly.png new file mode 100644 index 0000000000..c4eb18dd80 Binary files /dev/null and b/assets/app-icon/photocraft-nightly.png differ diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 8268a0641b..a5148afb1e 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -50,7 +50,7 @@ pub(crate) fn install(ctx: &egui::Context, fonts: &UiFonts<'_>, frame: Option, show_file_name: bool) -> String { + let Some((name, dirty)) = document else { return app_name.into() }; + let prefix = if dirty { "*" } else { "" }; + if show_file_name { format!("{prefix}{name} \u{2014} {app_name}") } else { format!("{prefix}{app_name}") } +} + +pub(crate) fn drawn_title(app_name: &str, document: Option<(&str, bool)>, show_file_name: bool, mark_document_channel: bool) -> String { + let Some((name, dirty)) = document else { return app_name.into() }; + let label = if show_file_name { name } else { app_name }; + let channel = if show_file_name && mark_document_channel { format!(" \u{2014} {app_name}") } else { String::new() }; + format!("{label}{channel}{}", if dirty { " •" } else { "" }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn nightly_native_caption_keeps_channel_across_document_dirty_and_hidden_name_updates() { + let channel = "PhotoCraft Nightly"; + assert_eq!(os_title(channel, None, true), channel); + for dirty in [false, true] { + let shown = os_title(channel, Some(("my document.psd", dirty)), true); + assert!(shown.contains("my document.psd")); + assert!(shown.ends_with(channel)); + assert_eq!(shown.starts_with('*'), dirty); + let hidden = os_title(channel, Some(("my document.psd", dirty)), false); + assert!(hidden.ends_with(channel)); + assert!(!hidden.contains("my document.psd")); + assert_eq!(hidden.starts_with('*'), dirty); + } + } + + #[test] + fn drawn_nightly_caption_keeps_channel_when_a_document_is_open() { + let channel = "PhotoCraft Nightly"; + for show_name in [false, true] { + for dirty in [false, true] { + let title = drawn_title(channel, Some(("work.psd", dirty)), show_name, true); + assert!(title.contains(channel)); + assert_eq!(title.contains("work.psd"), show_name); + assert_eq!(title.ends_with('•'), dirty); + } + } + } + + #[test] + fn stable_drawn_caption_preserves_the_document_only_style_and_dirty_dot() { + let stable = "PhotoCraft"; + assert_eq!(drawn_title(stable, None, true, false), stable); + let clean = drawn_title(stable, Some(("work.psd", false)), true, false); + assert_eq!(clean, "work.psd"); + let dirty = drawn_title(stable, Some(("work.psd", true)), true, false); + assert!(dirty.starts_with(&clean)); + assert!(dirty.ends_with('•')); + assert!(!dirty.contains(stable)); + let hidden = drawn_title(stable, Some(("work.psd", true)), false, false); + assert!(hidden.starts_with(stable)); + assert!(hidden.ends_with('•')); + assert!(!hidden.contains("work.psd")); + } +} diff --git a/crates/ui-egui/src/dialogs/credits.rs b/crates/ui-egui/src/dialogs/credits.rs index ebc6689f5a..d3518b9f33 100644 --- a/crates/ui-egui/src/dialogs/credits.rs +++ b/crates/ui-egui/src/dialogs/credits.rs @@ -79,16 +79,31 @@ pub fn credits() -> Credits { /// The About tab's contents: name, blurb, version, the community button and the project links. pub fn about_info(_app: &PhotocraftApp) -> AboutInfo { - AboutInfo::new("PhotoCraft", tl!("PhotoCraft — an open-source, native image editor written in Rust."), photocraft_engine::build_info::long_version()) + about_info_for(crate::os_window::identity(), photocraft_engine::build_info::long_version(), photocraft_engine::build_info::git_sha()) +} + +fn about_info_for(identity: crate::os_window::LaunchIdentity, version: String, commit: Option<&str>) -> AboutInfo { + let nightly = identity == crate::os_window::LaunchIdentity::NightlyV1; + let mut links = vec![ + AboutLink::new(tl!("PhotoCraft website"), crate::links::APP_PAGE), + AboutLink::new(tl!("GitHub"), crate::links::GITHUB), + AboutLink::new(tl!("ArtCraft"), crate::links::ARTCRAFT_WEBSITE), + ]; + if nightly { + // Opens only after a user click. No diagnostics, paths or documents are sent automatically. + links.push(AboutLink::new(tl!("Report a problem"), crate::links::ISSUES)); + } + let version = if nightly { nightly_about_version(&version, commit) } else { version }; + AboutInfo::new(crate::os_window::name_for(identity), tl!("PhotoCraft — an open-source, native image editor written in Rust."), version) .community(AboutLink::new(tl!("Join us on Discord"), crate::links::DISCORD)) - .links([ - AboutLink::new(tl!("PhotoCraft website"), crate::links::APP_PAGE), - AboutLink::new(tl!("GitHub"), crate::links::GITHUB), - AboutLink::new(tl!("ArtCraft"), crate::links::ARTCRAFT_WEBSITE), - ]) + .links(links) .built_with("egui · wgpu · photocraft-engine") } +fn nightly_about_version(version: &str, commit: Option<&str>) -> String { + format!("{version}\nCommit: {}", commit.filter(|value| !value.is_empty()).unwrap_or("unavailable")) +} + /// Opens the About dialog on `tab`. pub fn open_about(app: &mut PhotocraftApp, tab: AboutTab) -> DialogId { let dialog = HostedAbout::new(about_info(app), credits()).tab(tab); @@ -113,3 +128,44 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { ctx.copy_text(crate::gpu_status::system_info(app).join("\n")); } } + +#[cfg(test)] +mod nightly_about_tests { + use super::*; + use crate::os_window::LaunchIdentity; + + #[test] + fn stable_about_preserves_its_name_version_and_existing_links() { + let info = about_info_for(LaunchIdentity::Stable, "0.23.1 (dev build)".into(), None); + let expected = AboutInfo::new("PhotoCraft", "", "0.23.1 (dev build)".to_owned()); + assert_eq!(info.app_name, expected.app_name); + assert_eq!(info.version, expected.version); + assert_eq!( + info.links.iter().map(|link| link.url.as_str()).collect::>(), + [crate::links::APP_PAGE, crate::links::GITHUB, crate::links::ARTCRAFT_WEBSITE] + ); + assert_eq!(info.community.unwrap().url, crate::links::DISCORD); + } + + #[test] + fn nightly_about_names_its_channel_and_adds_a_user_initiated_report_link() { + let commit = "0123456789abcdef0123456789abcdef01234567"; + let version = "0.23.1-nightly.20261121.17.1.g0123456789ab"; + let info = about_info_for(LaunchIdentity::NightlyV1, version.into(), Some(commit)); + let expected = AboutInfo::new("PhotoCraft Nightly", "", nightly_about_version(version, Some(commit))); + assert_eq!(info.app_name, expected.app_name); + assert_eq!(info.version, expected.version); + assert_eq!(info.links.len(), 4); + assert_eq!(info.links.last().unwrap().url, crate::links::ISSUES); + assert_eq!(info.community.unwrap().url, crate::links::DISCORD); + } + + #[test] + fn nightly_about_retains_the_full_tag_and_commit_without_inventing_missing_provenance() { + let commit = "0123456789abcdef0123456789abcdef01234567"; + let version = "0.23.1-nightly.20261121.17.1.g0123456789ab"; + assert_eq!(nightly_about_version(version, Some(commit)), format!("{version}\nCommit: {commit}")); + assert_eq!(nightly_about_version(version, None), format!("{version}\nCommit: unavailable")); + assert_eq!(nightly_about_version(version, Some("")), format!("{version}\nCommit: unavailable")); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b70982f0d0..f09e0498e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -26,6 +26,7 @@ macro_rules! tl { } mod brush_mode_menu; pub mod canvas; +mod channel_titles; #[cfg(not(target_arch = "wasm32"))] pub mod control; pub mod dialogs; diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 4f20c241d7..35261c73ff 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -6,9 +6,59 @@ /// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon. pub const APP_ID: &str = "ai.storyteller.photocraft"; +/// Immutable startup identity. The desktop selects it before any UI/runtime service is created. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LaunchIdentity { + Stable, + NightlyV1, +} + +static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> { + let value = match identity { + LaunchIdentity::Stable => 1, + LaunchIdentity::NightlyV1 => 2, + }; + IDENTITY + .compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire) + .map(|_| ()) + .map_err(|_| "the window launch identity was already selected".into()) +} + +pub fn identity() -> LaunchIdentity { + if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable } +} + +pub const fn id_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => APP_ID, + LaunchIdentity::NightlyV1 => "ai.storyteller.photocraft.nightly-v1", + } +} + +pub fn app_id() -> &'static str { + id_for(identity()) +} + +pub const fn name_for(identity: LaunchIdentity) -> &'static str { + match identity { + LaunchIdentity::Stable => "PhotoCraft", + LaunchIdentity::NightlyV1 => "PhotoCraft Nightly", + } +} + +pub const fn stable_services_for(identity: LaunchIdentity) -> bool { + matches!(identity, LaunchIdentity::Stable) +} + +pub fn stable_services_allowed() -> bool { + stable_services_for(identity()) +} + /// A builder for an extra OS window, carrying [`APP_ID`]. pub fn builder() -> egui::ViewportBuilder { - egui::ViewportBuilder::default().with_app_id(APP_ID) + egui::ViewportBuilder::default().with_app_id(app_id()) } #[cfg(test)] @@ -18,3 +68,15 @@ mod tests { assert_eq!(super::builder().app_id.as_deref(), Some("ai.storyteller.photocraft")); } } + +#[cfg(test)] +mod profile_tests { + use super::*; + #[test] + fn nightly_identity_is_distinct_and_never_enables_stable_services() { + assert_eq!(id_for(LaunchIdentity::Stable), APP_ID); + assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID); + assert!(stable_services_for(LaunchIdentity::Stable)); + assert!(!stable_services_for(LaunchIdentity::NightlyV1)); + } +} diff --git a/crates/ui-egui/src/panels/title_bar.rs b/crates/ui-egui/src/panels/title_bar.rs index 5d99100419..020b4ec578 100644 --- a/crates/ui-egui/src/panels/title_bar.rs +++ b/crates/ui-egui/src/panels/title_bar.rs @@ -34,22 +34,28 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// no document open. With Preferences › Interface › Show File Name In Title off, the file name drops out and the app /// name (and the dot) remains, since the tabs already name the file (#5037). pub(crate) fn title_text(app: &PhotocraftApp) -> String { - let show_name = app.session.prefs().interface.show_file_name_in_title; - app.session - .active() - .map(|d| format!("{}{}", if show_name { d.doc.name.as_str() } else { "PhotoCraft" }, if d.is_dirty() { " •" } else { "" })) - .unwrap_or_else(|| "PhotoCraft".into()) + title_text_for(app, crate::os_window::identity()) } -/// The OS window title: the active document's name suffixed with the app name (a `*` prefix -/// marks unsaved changes, like the `•` in the app-drawn title), or just the app name with no -/// document open. With Preferences › Interface › Show File Name In Title off, the file name -/// drops out and only the app name (and the `*`) remains (#5037). +fn title_text_for(app: &PhotocraftApp, identity: crate::os_window::LaunchIdentity) -> String { + let document = app.session.active().map(|d| (d.doc.name.as_str(), d.is_dirty())); + crate::channel_titles::drawn_title( + crate::os_window::name_for(identity), + document, + app.session.prefs().interface.show_file_name_in_title, + identity == crate::os_window::LaunchIdentity::NightlyV1, + ) +} + +/// The OS window title retains its channel through document/dirty/preference changes. +/// Stable formatting is unchanged; Nightly never falls back to the stable brand name. pub fn window_title(app: &PhotocraftApp) -> String { - if !app.session.prefs().interface.show_file_name_in_title { - return format!("{}PhotoCraft", if app.session.active().is_some_and(|d| d.is_dirty()) { "*" } else { "" }); - } - app.session.active().map(|d| format!("{}{} \u{2014} PhotoCraft", if d.is_dirty() { "*" } else { "" }, d.doc.name)).unwrap_or_else(|| "PhotoCraft".into()) + window_title_for(app, crate::os_window::identity()) +} + +fn window_title_for(app: &PhotocraftApp, identity: crate::os_window::LaunchIdentity) -> String { + let document = app.session.active().map(|d| (d.doc.name.as_str(), d.is_dirty())); + crate::channel_titles::os_title(crate::os_window::name_for(identity), document, app.session.prefs().interface.show_file_name_in_title) } #[cfg(test)] diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index e004f9e2dd..29c3f08b32 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -8,7 +8,7 @@ use crate::PhotocraftApp; pub(crate) struct Runtime { /// The one checker: the startup prompt, the manual check, the installation and the last update's outcome. #[cfg(not(target_arch = "wasm32"))] - updater: craft::update::updater::Updater, + updater: Option, /// The check-result dialog on the dialog host, while one is open. #[cfg(not(target_arch = "wasm32"))] result_dialog: Option, @@ -17,11 +17,18 @@ pub(crate) struct Runtime { outcome_announced: bool, } +#[cfg(not(target_arch = "wasm32"))] +fn stable_updater(identity: crate::os_window::LaunchIdentity, make: impl FnOnce() -> T) -> Option { + crate::os_window::stable_services_for(identity).then(make) +} + impl Default for Runtime { fn default() -> Self { Self { #[cfg(not(target_arch = "wasm32"))] - updater: craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION), + updater: stable_updater(crate::os_window::identity(), || { + craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION) + }), #[cfg(not(target_arch = "wasm32"))] result_dialog: None, #[cfg(not(target_arch = "wasm32"))] @@ -33,7 +40,8 @@ impl Default for Runtime { /// Help ▸ Check for Updates: starts a check whose outcome the result window shows. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn check(app: &mut PhotocraftApp, _ctx: &egui::Context, _params: Value) -> Result { - app.updates_rt.updater.check_now(); + let updater = app.updates_rt.updater.as_mut().ok_or("Nightly updates are managed by ArtCraft Launcher")?; + updater.check_now(); app.ui.updates_open = true; Ok(serde_json::json!({"status": "checking"})) } @@ -49,12 +57,13 @@ pub(crate) fn check(_app: &mut PhotocraftApp, _ctx: &egui::Context, _params: Val #[cfg(not(target_arch = "wasm32"))] pub(crate) fn tick(app: &mut PhotocraftApp) { use craft::update::updater::Status; + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; if app.session.prefs().general.automatically_check_updates { - app.updates_rt.updater.check_at_start(); + updater.check_at_start(); } else { - app.updates_rt.updater.read_last_update(); + updater.read_last_update(); } - if !app.updates_rt.outcome_announced && matches!(app.updates_rt.updater.status(), Status::Updated(_) | Status::InstallFailed(_)) { + if !app.updates_rt.outcome_announced && matches!(updater.status(), Status::Updated(_) | Status::InstallFailed(_)) { app.updates_rt.outcome_announced = true; app.ui.updates_open = true; } @@ -77,8 +86,14 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // An update starts, and a ready one asks the app to close, only while no work is unsaved. let clean = !app.has_unsaved_work(); - app.updates_rt.updater.tick(ctx); - match app.updates_rt.updater.run(&mut app.framework.dialogs, clean) { + let action = match app.updates_rt.updater.as_mut() { + Some(updater) => { + updater.tick(ctx); + updater.run(&mut app.framework.dialogs, clean) + } + None => return, + }; + match action { Action::None => {} Action::OpenUrl(url) => { let _ = crate::links::open(app, ctx, &url); @@ -92,7 +107,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // A cancelled result (the dialog withdrawn below) answers nothing. if let Some(choice) = app.framework.dialogs.take::().and_then(|result| result.ok()) { app.updates_rt.result_dialog = None; - let updater = &mut app.updates_rt.updater; + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; match choice { CheckChoice::CheckNow | CheckChoice::CheckAgain => updater.check_now(), CheckChoice::RestartToUpdate => updater.restart_to_update(), @@ -105,7 +120,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } // An available release shows in the updater's prompt instead of the result window. - let updater = &app.updates_rt.updater; + let Some(updater) = app.updates_rt.updater.as_ref() else { return }; let wanted = app.ui.updates_open && *updater.status() != Status::Idle && !updater.prompt_open(); let status = updater.status().clone(); let dialogs = &mut app.framework.dialogs; @@ -124,7 +139,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { /// The updater's installation progress or error line, for `ui.inspect`. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn status_message(app: &PhotocraftApp) -> Option { - app.updates_rt.updater.status_message() + app.updates_rt.updater.as_ref()?.status_message() } /// The web build has no updater, so no message. @@ -136,7 +151,8 @@ pub(crate) fn status_message(_app: &PhotocraftApp) -> Option { /// Offers `version` as an available release, as a check at start would, for the snapshot example. #[cfg(not(target_arch = "wasm32"))] pub fn preview_release(app: &mut PhotocraftApp, version: &str, url: &str) { - app.updates_rt.updater.offer(craft::update::Release { + let Some(updater) = app.updates_rt.updater.as_mut() else { return }; + updater.offer(craft::update::Release { tag: format!("v{version}"), version: craft::update::parse_version(version), name: format!("PhotoCraft {version}"), @@ -168,17 +184,17 @@ mod tests { Err("offline".into()) }); let mut app = app(); - app.updates_rt.updater = craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION).with_source(source); + app.updates_rt.updater = Some(craft::update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION).with_source(source)); app.session.edit_prefs(|p| p.general.automatically_check_updates = false); tick(&mut app); assert!(checks.recv_timeout(Duration::from_millis(100)).is_err(), "no automatic check while the preference is off"); - assert_eq!(*app.updates_rt.updater.status(), craft::update::updater::Status::Idle); + assert_eq!(*app.updates_rt.updater.as_ref().unwrap().status(), craft::update::updater::Status::Idle); let ctx = app.ctx().clone(); menus::invoke(&mut app, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap(); assert!(app.ui.updates_open); - assert_ne!(*app.updates_rt.updater.status(), craft::update::updater::Status::Idle); + assert_ne!(*app.updates_rt.updater.as_ref().unwrap().status(), craft::update::updater::Status::Idle); assert!(checks.recv_timeout(Duration::from_secs(5)).is_ok(), "the manual check ran"); } @@ -203,3 +219,27 @@ mod tests { assert!(!app.ui.updates_open); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod profile_tests { + use super::*; + use crate::os_window::LaunchIdentity; + #[test] + fn a_nightly_never_even_constructs_the_stable_updater() { + let calls = std::cell::Cell::new(0); + let nightly = stable_updater(LaunchIdentity::NightlyV1, || { + calls.set(calls.get() + 1); + 42 + }); + assert_eq!(nightly, None); + assert_eq!(calls.get(), 0, "Updater::new reads stable installed-version state"); + assert_eq!( + stable_updater(LaunchIdentity::Stable, || { + calls.set(calls.get() + 1); + 42 + }), + Some(42) + ); + assert_eq!(calls.get(), 1); + } +} diff --git a/packaging/linux/nightly.sh b/packaging/linux/nightly.sh new file mode 100644 index 0000000000..ca9bc0893b --- /dev/null +++ b/packaging/linux/nightly.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks. +set -euo pipefail +ARCH= +while [[ $# -gt 0 ]]; do + case "$1" in + --arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;; + -h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;; + *) echo "unsupported nightly argument: $1" >&2; exit 2 ;; + esac +done +[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; } +. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh" +nightly_init linux "$ARCH" x86_64-unknown-linux-gnu +OUTPUT="$DIST/photocraft-$VERSION-linux-x86_64-nightly.tar.gz" +[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive' +nightly_build_gui +STAGE="$NIGHTLY_WORK/stage" +mkdir -p "$STAGE" +cp "$NIGHTLY_GUI" "$STAGE/photocraft" +chmod 755 "$STAGE/photocraft" +cp "$ROOT/assets/app-icon/photocraft-nightly.png" "$STAGE/photocraft-nightly.png" +nightly_copy_notices "$STAGE" +python3 "$ROOT/packaging/nightly-archive.py" linux "$STAGE" "$NIGHTLY_WORK/archive.tar.gz" +nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT" diff --git a/packaging/nightly-archive-tests.py b/packaging/nightly-archive-tests.py new file mode 100644 index 0000000000..c7cd4394ef --- /dev/null +++ b/packaging/nightly-archive-tests.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Synthetic app-owned archive/output tests; no native build or executable launch.""" +import gzip +import importlib.util +import os +from pathlib import Path +import subprocess +import tarfile +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py") +ARCHIVE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ARCHIVE) + + +class ArchivePolicy(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.stage = self.root / "stage" + self.stage.mkdir() + self.output = self.root / "nightly.tar.gz" + self.required = {"photocraft", "photocraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + for name in self.required: + (self.stage / name).write_bytes(b"generated fixture: " + name.encode()) + (self.stage / "photocraft").chmod(0o755) + + def test_flat_regular_ustar_with_all_notices(self): + (self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8") + ARCHIVE.linux_archive(self.stage, self.output) + with tarfile.open(self.output) as archive: + self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"}) + self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive)) + self.assertEqual(archive.extractfile("photocraft").read(), (self.stage / "photocraft").read_bytes()) + with gzip.open(self.output, "rb") as stream: + while (header := stream.read(512)) != bytes(512): + self.assertEqual(len(header), 512) + self.assertIn(header[156:157], {b"0", b"\0"}) + self.assertEqual(header[257:263], b"ustar\0") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + stream.read(((size + 511) // 512) * 512) + + def test_each_required_member_is_required_before_output(self): + for name in self.required: + with self.subTest(name=name): + content = (self.stage / name).read_bytes() + (self.stage / name).unlink() + with self.assertRaisesRegex(ValueError, "required"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + (self.stage / name).write_bytes(content) + + def test_unexpected_cli_portable_or_installer_member_refuses(self): + for name in ["photocraft-cli", "portable.txt", "photocraft.desktop"]: + with self.subTest(name=name): + bad = self.stage / name + bad.write_bytes(b"generated fixture") + with self.assertRaisesRegex(ValueError, "unexpected"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + bad.unlink() + + def test_symlink_refuses_before_output(self): + icon = self.stage / "photocraft-nightly.png" + icon.unlink() + icon.symlink_to(self.stage / "README.md") + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_directory_refuses_before_output(self): + icon = self.stage / "photocraft-nightly.png" + icon.unlink() + icon.mkdir() + with self.assertRaisesRegex(ValueError, "regular file"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_long_notice_refuses_before_output(self): + (self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "short regular"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_case_colliding_notices_refuse_before_output(self): + for name in ["OFL-Font.txt", "OFL-font.txt"]: + (self.stage / name).write_bytes(b"fixture") + with self.assertRaisesRegex(ValueError, "case-colliding"): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertFalse(self.output.exists()) + + def test_existing_archive_is_unchanged(self): + self.output.write_bytes(b"owned earlier artifact") + with self.assertRaises(FileExistsError): + ARCHIVE.linux_archive(self.stage, self.output) + self.assertEqual(self.output.read_bytes(), b"owned earlier artifact") + + +class ExclusiveOutput(unittest.TestCase): + def setUp(self): + self.scratch = tempfile.TemporaryDirectory() + self.addCleanup(self.scratch.cleanup) + self.root = Path(self.scratch.name) + self.source = self.root / "input archive" + self.output = self.root / "final archive" + self.source.write_bytes(b"generated archive fixture" * 1024) + + def publish(self): + return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15) + + def test_success_copies_exact_bytes(self): + result = self.publish() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.output.read_bytes(), self.source.read_bytes()) + + def test_existing_output_is_never_replaced(self): + self.output.write_bytes(b"existing artifact") + self.assertNotEqual(self.publish().returncode, 0) + self.assertEqual(self.output.read_bytes(), b"existing artifact") + + def test_missing_source_does_not_leave_a_fake_empty_artifact(self): + self.source.unlink() + self.assertNotEqual(self.publish().returncode, 0) + self.assertFalse(self.output.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/packaging/nightly-archive.py b/packaging/nightly-archive.py new file mode 100644 index 0000000000..5ca8081d33 --- /dev/null +++ b/packaging/nightly-archive.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Photo-owned flat Linux archive policy. No path alias/PAX/link records.""" +import pathlib +import re +import sys +import tarfile + +APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"} + + +def notice(name): + return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None + + +def linux_archive(stage, output): + entries = sorted(stage.iterdir(), key=lambda item: item.name) + folded = set() + for entry in entries: + name = entry.name + if name not in {"photocraft", "photocraft-nightly.png"} and not notice(name): + raise ValueError(f"unexpected nightly member: {name}") + if entry.is_symlink() or not entry.is_file() or len(name.encode("utf-8")) > 100: + raise ValueError(f"nightly member must be a short regular file: {name}") + if name.casefold() in folded: + raise ValueError(f"case-colliding nightly member: {name}") + folded.add(name.casefold()) + required = {"photocraft", "photocraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"} + if not required.issubset({item.name for item in entries}): + raise ValueError("required GUI/icon/notices missing") + with tarfile.open(output, "x:gz", format=tarfile.USTAR_FORMAT) as archive: + for entry in entries: + archive.add(entry, arcname=entry.name, recursive=False) + # Inspect the raw ordinary headers, not a transparent PAX/GNU-normalizing reader. + import gzip + with gzip.open(output, "rb") as stream: + while True: + header = stream.read(512) + if header == b"\0" * 512: + break + if len(header) != 512 or header[156:157] not in {b"0", b"\0"}: + raise ValueError("non-ordinary TAR record was emitted") + size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8) + remaining = ((size + 511) // 512) * 512 + while remaining: + chunk = stream.read(min(remaining, 1024 * 1024)) + if not chunk: + raise ValueError("truncated TAR member") + remaining -= len(chunk) + + +if __name__ == "__main__": + if len(sys.argv) != 4 or sys.argv[1] != "linux": + raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT") + linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3])) diff --git a/packaging/nightly-common.sh b/packaging/nightly-common.sh new file mode 100644 index 0000000000..8f9514169f --- /dev/null +++ b/packaging/nightly-common.sh @@ -0,0 +1,72 @@ +# shellcheck shell=bash +# Shared setup for app-owned native nightly archives; stable packaging does not source this file. + +nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; } + +nightly_init() { + local os="$1" arch="$2" target="$3" date_digits + [[ "${PHOTOCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'PHOTOCRAFT_BUILD_CHANNEL must be nightly-v1' + [[ "${PHOTOCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required' + [[ "${PHOTOCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required' + [[ "${PHOTOCRAFT_VERSION##*.g}" == "${PHOTOCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch' + [[ "${PHOTOCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required' + date_digits="${PHOTOCRAFT_VERSION#*-nightly.}" + date_digits="${date_digits%%.*}" + [[ "${PHOTOCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch' + [[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required' + [[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required' + [[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal' + ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PHOTOCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit' + [[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source' + if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then + nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory' + fi + # env.sh retains the established notice copier. Required values above prohibit its stable fallbacks. + . "$ROOT/packaging/env.sh" + export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch" + NIGHTLY_RUST_TARGET="$target" + mkdir -p "$CARGO_TARGET_DIR" + NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")" + trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT +} + +nightly_build_gui() { + (cd "$ROOT" && PHOTOCRAFT_OVERRIDE_VERSION="$VERSION" cargo build --release --locked -p photocraft --features heif --target "$NIGHTLY_RUST_TARGET") + NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/photocraft" + [[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable' + local actual + actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed' + [[ "$actual" == "PhotoCraft $VERSION (nightly-v1)" ]] || nightly_die 'the built version/flavor is not the prepared identity' + [[ "$(git -C "$ROOT" rev-parse HEAD)" == "$PHOTOCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build' +} + +nightly_copy_notices() { + local destination="$1" required + for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do + [[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required" + done + copy_docs "$destination" +} + +nightly_publish_archive() { + # Exclusive creation: never replace an existing artifact, even if another writer raced the preflight. + python3 - "$1" "$2" <<'PY' +import os, shutil, sys +source, destination = sys.argv[1:] +created = False +try: + # Open the input first: a missing source must not leave an empty final artifact. + with open(source, 'rb') as incoming: + with open(destination, 'xb') as output: + created = True + shutil.copyfileobj(incoming, output, length=1024 * 1024) + output.flush() + os.fsync(output.fileno()) +except BaseException: + if created: + os.unlink(destination) + raise +PY + printf 'Nightly artifact: %s\n' "$2" +} diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 new file mode 100644 index 0000000000..de820fdc61 --- /dev/null +++ b/packaging/windows/nightly-package-tests.ps1 @@ -0,0 +1,56 @@ +param([Parameter(Mandatory=$true)][string] $FixtureRoot) +. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly +function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } } +$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64' +Assert ($spec.Archive -eq 'photocraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name' +Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'photocraft.exe') 'nightly must not ship the unqualified CLI' +Assert ($spec.AppId -eq 'ai.storyteller.photocraft.nightly-v1') 'nightly identity is not distinct' +foreach ($arch in @('x86', 'arm64')) { + $refused = $false + try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true } + Assert $refused 'unsupported target was accepted' +} +foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) { + $refused = $false + try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true } + Assert $refused 'unsafe artifact version was accepted' +} +Assert-NightlyFlavor 'PhotoCraft Nightly' 'PhotoCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345' +foreach ($pair in @(@('PhotoCraft', 'PhotoCraft 0.23.1 (nightly-v1)'), @('PhotoCraft Nightly', 'PhotoCraft 0.23.1'))) { + $refused = $false + try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true } + Assert $refused 'stable or mismatched build flavor was accepted' +} +Write-Output 'nightly packaging spec, target/version refusal and flavor-binding tests passed' + +# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP. +if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' } +$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N')) +try { + $repo = Join-Path $testRoot 'app' + $fontRepo = Join-Path $testRoot 'craft-fonts' + $family = Join-Path $fontRepo 'fonts\ExampleFamily' + $stage = Join-Path $testRoot 'stage' + New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null + $rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') + foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" } + Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example' + Copy-NightlyNotices $repo $fontRepo $stage + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { + Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name" + } + $zip = Join-Path $testRoot 'notices.zip' + Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip + $archive = [IO.Compression.ZipFile]::OpenRead($zip) + try { + $names = @($archive.Entries | ForEach-Object { $_.FullName }) + foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" } + foreach ($forbidden in @('portable.txt', 'photocraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" } + $entry = $archive.GetEntry('OFL-ExampleFamily.txt') + $reader = [IO.StreamReader]::new($entry.Open()) + try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} finally { + if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force } +} +Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP' diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 new file mode 100644 index 0000000000..0671787730 --- /dev/null +++ b/packaging/windows/nightly.ps1 @@ -0,0 +1,102 @@ +<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #> +param( + [string] $Arch = 'x64', + [string] $Version, + [string] $Target, + [string] $TargetDir, + [string] $Dist, + [switch] $SkipBuild, + [switch] $FunctionsOnly +) +$ErrorActionPreference = 'Stop' + +function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { + if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' } + if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' } + return @{ + Archive = "photocraft-$Version-windows-x86_64-nightly.zip" + Executables = @('photocraft.exe') + Channel = 'nightly-v1' + AppId = 'ai.storyteller.photocraft.nightly-v1' + } +} + +function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) { + if ($ProductName -ne 'PhotoCraft Nightly' -or $VersionOutput -cne "PhotoCraft $ExpectedVersion (nightly-v1)") { + throw 'the executable is not the compiled nightly-v1 flavor' + } +} + + +function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) { + foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') { + $source = Join-Path $RepositoryRoot $name + if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination } + } + if ($FontRepository) { + $fonts = Join-Path $FontRepository 'fonts' + if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' } + foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) { + $license = Join-Path $family.FullName 'OFL.txt' + if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") } + } + } +} + +if ($FunctionsOnly) { return } +if (-not $env:PHOTOCRAFT_VERSION -or $Version -cne $env:PHOTOCRAFT_VERSION) { throw 'nightly-v1 requires explicit PHOTOCRAFT_VERSION, not the Cargo version fallback' } +$Spec = Get-NightlyArchiveSpec $Version $Arch +if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' } +if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' } +$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$oldChannel = $env:PHOTOCRAFT_BUILD_CHANNEL +$oldVersionOverride = $env:PHOTOCRAFT_OVERRIDE_VERSION +try { + $env:PHOTOCRAFT_BUILD_CHANNEL = 'nightly-v1' + $env:PHOTOCRAFT_OVERRIDE_VERSION = $Version + $env:PHOTOCRAFT_REQUIRE_WINRES = '1' + $env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static' + cargo build --release --locked -p photocraft --features heif --target $Target + if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" } +} finally { + $env:PHOTOCRAFT_BUILD_CHANNEL = $oldChannel + $env:PHOTOCRAFT_OVERRIDE_VERSION = $oldVersionOverride +} +$Exe = Join-Path $TargetDir "$Target\release\photocraft.exe" +$pe = [System.IO.File]::ReadAllBytes($Exe) +if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } +$offset = [BitConverter]::ToInt32($pe, 0x3C) +if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' } +if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) { + throw 'nightly executable must be x86_64 Windows GUI' +} +$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo +$ProductName = $VersionInfo.ProductName +if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' } +# Check the embedded build flavor before invoking even the side-effect-free version query. +if ($ProductName -ne 'PhotoCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' } +$VersionOutput = (& $Exe --version | Out-String).Trim() +if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' } +Assert-NightlyFlavor $ProductName $VersionOutput $Version +$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64' +if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force } +New-Item -ItemType Directory -Force -Path $Stage | Out-Null +Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'photocraft.exe') +# Reuse existing signing policy; this script does not discover or change any signing secret. +& (Join-Path $PSScriptRoot 'sign.ps1') (Join-Path $Stage 'photocraft.exe') +Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage +if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) { + throw 'nightly stage contains an unexpected executable or portable fallback marker' +} +New-Item -ItemType Directory -Force -Path $Dist | Out-Null +$Zip = Join-Path $Dist $Spec.Archive +if (Test-Path -LiteralPath $Zip) { Remove-Item -LiteralPath $Zip -Force } +Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip +$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip) +try { + $Names = @($Archive.Entries | ForEach-Object { $_.FullName }) + if ('photocraft.exe' -notin $Names -or 'photocraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) { + throw 'nightly ZIP payload violates the GUI-only profile contract' + } +} finally { $Archive.Dispose() } +Write-Output "Nightly artifact: $Zip ($VersionOutput)" diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index d984e3930a..032c53c917 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -23,7 +23,8 @@ #> param( [ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64', - [switch] $SkipBuild + [switch] $SkipBuild, + [switch] $Nightly ) $ErrorActionPreference = 'Stop' $Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path @@ -57,7 +58,14 @@ if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).T Write-Output "PhotoCraft $Version for Windows $Arch ($Target)" +if ($Nightly) { + & (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild + return +} + if (-not $SkipBuild) { + $env:PHOTOCRAFT_BUILD_CHANNEL = 'stable' + # Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and # proc-macros are unaffected. $flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS' @@ -85,6 +93,9 @@ foreach ($check in @(@('photocraft.exe', 2), @('photocraft-cli.exe', 3))) { if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" } Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)" } +if ((Get-Item -LiteralPath (Join-Path $Bin 'photocraft.exe')).VersionInfo.ProductName -eq 'PhotoCraft Nightly') { + throw 'a nightly executable cannot be packaged as stable' +} $Stage = Join-Path $TargetDir "windows-package\$Arch" Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue New-Item -ItemType Directory -Force -Path $Stage | Out-Null