diff --git a/apps/photocraft-cli/build.rs b/apps/photocraft-cli/build.rs index 8983b9c8d6..c1e78c550a 100644 --- a/apps/photocraft-cli/build.rs +++ b/apps/photocraft-cli/build.rs @@ -1,15 +1,21 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft-cli.exe`. //! -//! On every other target this does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A +//! On every other target the Windows part does nothing, even when `PHOTOCRAFT_REQUIRE_WINRES` is set. A //! missing resource compiler is a warning, so a cross-compile from macOS or Linux still links, //! unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the release packaging script) turns it into a //! build error. +#[path = "../photocraft/git_checkout.rs"] +mod git_checkout; + /// Embeds the Windows resources and delay-loads the print-only system DLLs (#8272). fn main() -> std::io::Result<()> { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico"); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES"); + println!("cargo:rerun-if-changed=../photocraft/git_checkout.rs"); + git_checkout::emit(); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return Ok(()); } diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index 6e21c2ac44..5113c2c04a 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -3,6 +3,9 @@ fn main() { // May re-execute this process with glibc tuned to return freed document memory (#8743). photocraft_engine::malloc_tuning::apply(); + // The git commit of a dev build's checkout, for `--version` (build.rs, #5247). Before `run`: + // clap reads the version string once. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap, // not panic before anything is printed (issue #1108). let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index a4bcba0756..f49abe6a17 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -1,9 +1,12 @@ -//! Windows only: embed the app icon and version info (VERSIONINFO) into `photocraft.exe`. +//! Records the checkout's git commit for `--version` (`git_checkout.rs`, every target), and on +//! Windows only embeds the app icon and version info (VERSIONINFO) into `photocraft.exe`. //! -//! On every other target this does nothing. A missing resource compiler is a warning, so a +//! On every other target the Windows part does nothing. A missing resource compiler is a warning, so a //! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the //! release workflow) turns it into an error. +mod git_checkout; + #[path = "src/build_channel.rs"] mod build_channel; @@ -27,6 +30,8 @@ fn main() { 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-changed=git_checkout.rs"); + git_checkout::emit(); println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION"); let built_version = if nightly { match std::env::var("PHOTOCRAFT_VERSION") { diff --git a/apps/photocraft/git_checkout.rs b/apps/photocraft/git_checkout.rs new file mode 100644 index 0000000000..38cfa185ec --- /dev/null +++ b/apps/photocraft/git_checkout.rs @@ -0,0 +1,71 @@ +//! Build-script helper shared by the `photocraft` and `photocraft-cli` binaries: the git commit +//! of the source checkout, so a plain `cargo build` from git reports `0.8.2 (dev build, 6f8505421)` +//! (#5247). Release builds set `PHOTOCRAFT_BUILD_SHA` instead and are left alone; without git or +//! outside a checkout of this workspace (a source tarball) nothing is set and the build stays +//! `(dev build)`. The binaries pass the value to `photocraft_engine::build_info::set_checkout`. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Runs `git ` in `dir`; its trimmed output when it succeeds. +fn git(dir: &Path, args: &[&str]) -> Option { + let out = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?; + let s = String::from_utf8(out.stdout).ok()?.trim().to_string(); + (out.status.success() && !s.is_empty()).then_some(s) +} + +/// Emits `PHOTOCRAFT_CHECKOUT_SHA` for the crate whose build script calls it. +pub fn emit() { + println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_SHA"); + if std::env::var("PHOTOCRAFT_BUILD_SHA").is_ok_and(|s| !s.trim().is_empty()) { + return; + } + let Some(manifest) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else { return }; + // apps/ → the workspace root. A tarball unpacked inside some other repository must not + // report that repository's commit. + let Some(root) = manifest.parent().and_then(Path::parent).and_then(|r| r.canonicalize().ok()) else { return }; + let Some(top) = git(&root, &["rev-parse", "--show-toplevel"]).and_then(|t| PathBuf::from(t).canonicalize().ok()) else { return }; + if top != root { + return; + } + // Watch before asking for the commit: on an unborn branch `rev-parse HEAD` fails, and the + // first commit must still re-run this script. + for path in watch_paths(&root) { + println!("cargo:rerun-if-changed={}", path.display()); + } + let Some(sha) = git(&root, &["rev-parse", "HEAD"]) else { return }; + println!("cargo:rustc-env=PHOTOCRAFT_CHECKOUT_SHA={sha}"); +} + +/// The git files whose change means HEAD moved: a commit or checkout changes HEAD (detached) or the +/// branch's ref. Cargo treats a watched path that does not exist as always changed (it re-runs the +/// build script and recompiles the binary on every build), so only existing paths are returned. +pub(crate) fn watch_paths(root: &Path) -> Vec { + let mut paths = Vec::new(); + if let Some(dir) = git(root, &["rev-parse", "--absolute-git-dir"]) { + let head = Path::new(&dir).join("HEAD"); + paths.extend(watched(&head, &head)); + } + let Some(common) = git(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"]) else { return paths }; + let common = Path::new(&common); + if git(root, &["rev-parse", "--show-ref-format"]).as_deref() == Some("reftable") { + // Every ref update in a reftable repository rewrites the table stack. + let tables = common.join("reftable").join("tables.list"); + paths.extend(watched(&tables, &tables)); + return paths; + } + if let Some(head_ref) = git(root, &["symbolic-ref", "-q", "HEAD"]) { + // A packed or unborn branch has no loose ref file; the first commit on it creates one, + // which changes the nearest existing directory above it under `refs/`. + paths.extend(watched(&common.join(&head_ref), &common.join("refs"))); + } + let packed = common.join("packed-refs"); + paths.extend(watched(&packed, &packed)); + paths +} + +/// The path Cargo should watch for `path`: `path` itself when it exists, else its nearest existing +/// ancestor that is still inside `stop`; `None` when neither exists. +pub(crate) fn watched(path: &Path, stop: &Path) -> Option { + path.ancestors().take_while(|p| p.starts_with(stop)).find(|p| p.exists()).map(Path::to_path_buf) +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 85f44aa191..b8e0a15926 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -495,6 +495,8 @@ fn main() -> eframe::Result { // 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(); + // The git commit of a dev build's checkout, for `--version` and About (build.rs, #5247). + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); // Then, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); diff --git a/apps/photocraft/tests/it/command_line_usage.rs b/apps/photocraft/tests/it/command_line_usage.rs index a0d8377638..116e1440c8 100644 --- a/apps/photocraft/tests/it/command_line_usage.rs +++ b/apps/photocraft/tests/it/command_line_usage.rs @@ -88,6 +88,9 @@ fn help_wins_over_later_arguments() { fn version_prints_the_long_version() { let Run { status, stdout, .. } = run_photocraft(&["--version", "--safegpu"]); assert_eq!(status.code(), Some(0)); + // The binary records its checkout's commit at startup (#5247); the build script hands the + // same value to this test. + photocraft_engine::build_info::set_checkout(option_env!("PHOTOCRAFT_CHECKOUT_SHA")); assert_eq!(stdout, format!("photocraft {}\n", photocraft_engine::build_info::long_version())); } diff --git a/apps/photocraft/tests/it/git_checkout.rs b/apps/photocraft/tests/it/git_checkout.rs new file mode 100644 index 0000000000..8b05503e78 --- /dev/null +++ b/apps/photocraft/tests/it/git_checkout.rs @@ -0,0 +1,152 @@ +//! The build-script helper `git_checkout.rs` (#5247): Cargo re-runs a build script on every build +//! when a `rerun-if-changed` path is missing, so only existing paths may be watched. + +#[allow(dead_code)] +#[path = "../../git_checkout.rs"] +mod helper; + +use helper::{watch_paths, watched}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("photocraft-git-checkout-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("scratch dir"); + dir +} + +#[test] +fn an_existing_path_is_watched_itself() { + let git = scratch("exists"); + let packed = git.join("packed-refs"); + fs::write(&packed, "").expect("write"); + assert_eq!(watched(&packed, &packed), Some(packed.clone())); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_missing_file_with_no_room_to_climb_is_not_watched() { + let git = scratch("missing"); + let packed = git.join("packed-refs"); + assert_eq!(watched(&packed, &packed), None); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn a_packed_branch_watches_the_nearest_existing_ref_directory() { + let git = scratch("packed-branch"); + let refs = git.join("refs"); + fs::create_dir_all(refs.join("heads")).expect("refs/heads"); + // `refs/heads/fix/5247` with no `fix/` directory yet: watch `refs/heads`. + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads"))); + // Once the loose ref exists it is watched directly. + fs::create_dir_all(refs.join("heads/fix")).expect("refs/heads/fix"); + fs::write(refs.join("heads/fix/5247"), "abc\n").expect("loose ref"); + assert_eq!(watched(&refs.join("heads/fix/5247"), &refs), Some(refs.join("heads/fix/5247"))); + let _ = fs::remove_dir_all(&git); +} + +#[test] +fn the_search_never_leaves_the_stop_directory() { + let git = scratch("stop"); + // `refs/` itself is missing: its parent (the git dir) exists but is outside `stop`. + assert_eq!(watched(&git.join("refs/heads/main"), &git.join("refs")), None); + let _ = fs::remove_dir_all(&git); +} + +/// `git` with the variables that point it at another repository or pick its ref format removed, +/// so a fixture is the repository in its own directory whatever the environment says. +fn git() -> Command { + let mut c = Command::new("git"); + for var in ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_DEFAULT_REF_FORMAT"] { + c.env_remove(var); + } + c +} + +/// `git init` in a fresh scratch directory with `args`; `None` when this git cannot do it. The +/// files ref format unless `args` ask for another, whatever `init.defaultRefFormat` says (older +/// git ignores the setting). +fn init(name: &str, args: &[&str]) -> Option { + let dir = scratch(name); + let mut cmd = git(); + if !args.iter().any(|a| a.starts_with("--ref-format")) { + cmd.args(["-c", "init.defaultRefFormat=files"]); + } + let ok = cmd.arg("init").arg("-q").args(args).arg(&dir).status().is_ok_and(|s| s.success()); + if ok { + dir.canonicalize().ok() + } else { + let _ = fs::remove_dir_all(&dir); + None + } +} + +fn git_dir(root: &Path) -> PathBuf { + root.join(".git") +} + +/// `watch_paths(root)` canonicalised, so git's `C:/…` output compares equal to the scratch path on +/// Windows and `/var` to `/private/var` on macOS. Panics if any watched path is missing. +fn watched_in(root: &Path) -> Vec { + watch_paths(root).iter().map(|p| p.canonicalize().unwrap_or_else(|e| panic!("{} is watched but missing: {e}", p.display()))).collect() +} + +#[test] +fn an_unborn_branch_still_watches_head_and_the_ref_directory() { + // Before the first commit `rev-parse HEAD` fails; the first commit creates refs/heads/main, + // which must re-run the build script. + let Some(root) = init("unborn", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + assert!(paths.iter().any(|p| p.starts_with(git.join("refs"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_reftable_checkout_watches_the_table_stack() { + // Branch updates in a reftable repository rewrite reftable/tables.list, not a loose ref or + // packed-refs. Needs git 2.45 or newer; older git cannot create the repository. + let Some(root) = init("reftable", &["-b", "main", "--ref-format=reftable"]) else { + eprintln!("git without reftable support, skipped"); + return; + }; + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("reftable").join("tables.list")), "{paths:?}"); + assert!(paths.contains(&git.join("HEAD")), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn a_files_checkout_watches_the_branch_ref_and_not_a_table_stack() { + let Some(root) = init("files", &["-b", "main"]) else { + eprintln!("git init unavailable, skipped"); + return; + }; + fs::write(git_dir(&root).join("packed-refs"), "").expect("packed-refs"); + let paths = watched_in(&root); + let git = git_dir(&root); + assert!(paths.contains(&git.join("packed-refs")), "{paths:?}"); + assert!(!paths.iter().any(|p| p.starts_with(git.join("reftable"))), "{paths:?}"); + let _ = fs::remove_dir_all(&root); +} + +#[test] +fn outside_a_repository_nothing_is_watched() { + let dir = scratch("no-repo"); + // GIT_CEILING_DIRECTORIES is not set here, so a scratch dir inside a checkout would find it; + // the system temp dir is not inside one on CI or on a developer machine. + if git().arg("-C").arg(&dir).args(["rev-parse", "--git-dir"]).output().is_ok_and(|o| o.status.success()) { + eprintln!("temp dir is inside a git repository, skipped"); + } else { + assert!(watched_in(&dir).is_empty()); + } + let _ = fs::remove_dir_all(&dir); +} diff --git a/apps/photocraft/tests/it/main.rs b/apps/photocraft/tests/it/main.rs index 73bea9196a..f0248ad210 100644 --- a/apps/photocraft/tests/it/main.rs +++ b/apps/photocraft/tests/it/main.rs @@ -2,6 +2,7 @@ mod command_line_usage; mod control_exit_code; +mod git_checkout; mod startup_without_display; /// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid. diff --git a/crates/engine-core/src/build_info.rs b/crates/engine-core/src/build_info.rs index 3ad4da1aba..76267af92a 100644 --- a/crates/engine-core/src/build_info.rs +++ b/crates/engine-core/src/build_info.rs @@ -8,7 +8,11 @@ //! - `PHOTOCRAFT_BUILD_DATE`: the build date, conventionally `YYYY-MM-DD` //! //! Without them (a plain `cargo build`) the build reports itself as a dev build. Nothing here -//! shells out to git, so builds work from a source tarball and for wasm. +//! shells out to git, so builds work from a source tarball and for wasm. The desktop and CLI +//! binaries' build scripts do read the commit of a git checkout and hand it over with +//! [`set_checkout`] at startup, so a dev build from git says which commit it is +//! (`0.1.0 (dev build, 3f2a9c1d0)`); keeping it out of this crate means a commit doesn't rebuild +//! the engine. /// The workspace version, such as `0.1.0` or `0.2.0-rc.1`. pub const VERSION: &str = match option_env!("PHOTOCRAFT_OVERRIDE_VERSION") { @@ -31,12 +35,30 @@ pub fn build_date() -> Option<&'static str> { /// The commit shortened for display. pub fn short_sha() -> Option<&'static str> { - git_sha().map(|s| &s[..s.len().min(9)]) + git_sha().map(shorten) } -/// `0.1.0 (3f2a9c1d0, 2026-10-01)`, or `0.1.0 (dev build)` without provenance. +fn shorten(sha: &str) -> &str { + sha.get(..9).unwrap_or(sha) +} + +static CHECKOUT: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Records the git commit of the checkout a dev build was compiled from (the binaries' build +/// scripts read it; `None` or empty from a source tarball). Only the first call counts. +pub fn set_checkout(sha: Option<&str>) { + if let Some(sha) = sha.map(str::trim).filter(|s| !s.is_empty()) { + let _ = CHECKOUT.set(sha.to_string()); + } +} + +/// `0.1.0 (3f2a9c1d0, 2026-10-01)`; a dev build `0.1.0 (dev build, 3f2a9c1d0)` from a git +/// checkout, or `0.1.0 (dev build)` without provenance. pub fn long_version() -> String { - format_long(VERSION, short_sha(), build_date()) + match short_sha() { + Some(s) => format_long(VERSION, Some(s), build_date()), + None => format_dev(VERSION, CHECKOUT.get().map(|s| shorten(s)), build_date()), + } } /// [`long_version`] worked out once, for a `&'static str` such as clap's `version`. @@ -54,6 +76,14 @@ fn format_long(version: &str, sha: Option<&str>, date: Option<&str>) -> String { } } +/// A build without `PHOTOCRAFT_BUILD_SHA`: the checkout's commit, when known, marked as a dev build. +fn format_dev(version: &str, checkout: Option<&str>, date: Option<&str>) -> String { + match checkout { + Some(c) => format!("{version} (dev build, {c})"), + None => format_long(version, None, date), + } +} + #[cfg(test)] mod tests { use super::*; @@ -64,6 +94,11 @@ mod tests { assert_eq!(format_long("1.2.3", Some("abc"), None), "1.2.3 (abc)"); assert_eq!(format_long("1.2.3", None, Some("2026-10-01")), "1.2.3 (2026-10-01)"); assert_eq!(format_long("1.2.3-rc.1", None, None), "1.2.3-rc.1 (dev build)"); + // #5247: a dev build from a git checkout names its commit. + assert_eq!(format_dev("0.8.2", Some(shorten("6f8505421abcdef")), None), "0.8.2 (dev build, 6f8505421)"); + assert_eq!(format_dev("0.8.2", None, None), "0.8.2 (dev build)"); + assert_eq!(format_dev("0.8.2", None, Some("2026-10-01")), "0.8.2 (2026-10-01)"); + assert_eq!(shorten("abc"), "abc"); } #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2af53fa990..8261324fde 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -246,6 +246,9 @@ mod doc_window_dialog_tests; #[cfg(test)] mod document_window_title_tests; +#[cfg(test)] +mod arrange_window_origin_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs b/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs new file mode 100644 index 0000000000..f55fd61e61 --- /dev/null +++ b/crates/ui-egui/src/canvas/arrange_window_origin_tests.rs @@ -0,0 +1,281 @@ +//! #16883: Window › Arrange opens a floating document window over the app window's document area. The document +//! area is the app window's own rect, in the app window's own points; the place a window opens at is a rect on the +//! desktop. Every test here stands the app window away from the screen's origin, so the two differ, and builds the +//! expected places from the app's own geometry: the window's rect as the host reports it and the document area the +//! app drew in its last pass. + +use egui::{Context, Pos2, Rect, ViewportId, ViewportIdMap, ViewportInfo}; +use serde_json::json; + +use crate::PhotocraftApp; + +/// The app window as the host reports it: 1000 x 720 desktop points, its top-left far from the screen's origin, as +/// the reference measurement of #16883 had it (the app window at 816, 414). +fn app_window() -> Rect { + Rect::from_min_size(Pos2::new(760.0, 300.0), egui::vec2(1000.0, 720.0)) +} + +/// One pass in the order eframe runs them (`logic` before `ui`), with the app window reported at `window` on the +/// desktop, or with no rect reported at all when `window` is `None`, and `scale` pixels per point. +fn pass(app: &mut PhotocraftApp, ctx: &Context, window: Option, scale: f32) { + use eframe::App as _; + let local = Rect::from_min_size(Pos2::ZERO, window.unwrap_or_else(app_window).size()); + let mut viewports = ViewportIdMap::default(); + // egui needs the ROOT entry either way; without a rect the host has told the app nothing about where its window + // stands, which is the case before the first pass and on the fallback layer. + viewports.insert( + ViewportId::ROOT, + match window { + Some(window) => ViewportInfo { + inner_rect: Some(window), + outer_rect: Some(window), + focused: Some(true), + native_pixels_per_point: Some(scale), + minimized: Some(false), + ..Default::default() + }, + None => ViewportInfo { focused: Some(true), native_pixels_per_point: Some(scale), ..Default::default() }, + }, + ); + let mut input = egui::RawInput { viewport_id: ViewportId::ROOT, screen_rect: Some(local), viewports, focused: true, ..Default::default() }; + app.raw_input_hook(ctx, &mut input); + let mut frame = eframe::Frame::_new_kittest(); + let mut output = ctx.run_ui(input, |ui| { + app.logic(ui.ctx(), &mut frame); + app.ui(ui, &mut frame); + }); + output.textures_delta.clear(); +} + +/// The app with `documents` documents, its window standing at `window` on the desktop (nowhere reported when +/// `window` is `None`) at `scale`, through the passes that lay the document area out. Document windows open as OS +/// windows of their own, as the desktop integration runs them. +fn desktop(documents: usize, window: Option, scale: f32) -> (Box, Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for i in 0..documents { + app.run("file.new", json!({ "width": 300 + 40 * i as u32, "height": 220, "name": format!("doc {i}") })).unwrap(); + } + app.sync_views(); + let ctx = app.ctx().clone(); + PhotocraftApp::setup_context(&ctx, Default::default()); + ctx.set_embed_viewports(false); + for _ in 0..3 { + pass(&mut app, &ctx, window, scale); + } + (app, ctx) +} + +/// Runs an Arrange command and returns the floating windows it left, in order. +fn arranged(app: &mut PhotocraftApp, ctx: &Context, command: &str, params: serde_json::Value) -> Result { + crate::menus::invoke(app, ctx, &format!("window.arrange.{command}"), params) +} + +/// The windows' rects on the desktop, in the order the app lists its floating windows. +fn placed(app: &PhotocraftApp) -> Vec { + app.ui.document_windows.floating.iter().map(|(_, rect)| *rect).collect() +} + +/// The document area where the app window stands: the rect the app drew its canvas in, moved from the app window's +/// own points into desktop points. +fn area_on_desktop(app: &PhotocraftApp, window: Rect) -> Rect { + Rect::from_min_size(app.last_canvas_rect.min + window.min.to_vec2(), app.last_canvas_rect.size()) +} + +/// The passes placed a document area of their own inside the app window: the tests compare against that rect, not a +/// literal one, so they read what the app really has. +fn assert_real_document_area(app: &PhotocraftApp, window: Rect) { + let canvas = app.last_canvas_rect; + assert!(canvas.is_positive(), "the passes laid out a document area: {canvas:?}"); + let local = Rect::from_min_size(Pos2::ZERO, window.size()); + assert!(local.contains(canvas.min) && local.contains(canvas.max), "the document area is in the app window's own points: {canvas:?} in {local:?}"); + assert!(canvas.width() < window.width() && canvas.height() < window.height(), "the document area is part of the window, not all of it: {canvas:?}"); +} + +#[test] +fn float_in_window_opens_its_window_over_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + assert_real_document_area(&app, window); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let windows = placed(&app); + let first = windows.last().copied().expect("one floating window"); + assert_eq!(windows.len(), 1, "one window for the one document"); + assert!((first.min - area.min).length() < 0.5, "the window opens at the document area's top-left on the desktop: {first:?}, the area is {area:?}"); + assert!(area.contains(first.min), "so its top-left lies over the document area: {first:?} in {area:?}"); + assert!((first.size() - area.size() * 0.5).length() < 0.5, "the window still takes half the document area: {first:?} of {area:?}"); + assert!( + (first.min - app.last_canvas_rect.min).length() > 100.0, + "the document area's own points are not a desktop place: {first:?} against the window's own {area:?}" + ); +} + +#[test] +fn float_all_in_windows_cascades_from_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(3, Some(window), 1.0); + assert_real_document_area(&app, window); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatAllInWindows", json!({})).expect("every document gets a window"); + let windows = placed(&app); + assert_eq!(windows.len(), 3, "one window per document"); + assert!((windows[0].min - area.min).length() < 0.5, "the first window at the document area's top-left: {windows:?}, the area is {area:?}"); + for pair in windows.windows(2) { + let (before, next) = (pair[0], pair[1]); + assert!(next.min.x > before.min.x && next.min.y > before.min.y, "each next window steps down and across: {before:?} then {next:?}"); + assert!(area.contains(next.min), "and opens over the document area: {next:?} in {area:?}"); + } + assert!(windows.iter().all(|rect| (rect.size() - area.size() * 0.5).length() < 0.5), "every window takes half the document area: {windows:?}"); +} + +#[test] +fn new_window_for_document_opens_over_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "newWindowForDocument", json!({})).expect("a second view opens"); + let windows = placed(&app); + assert_eq!(windows.len(), 1, "one new window"); + assert!((windows[0].min - area.min).length() < 0.5, "the second view opens at the document area's top-left: {windows:?}, the area is {area:?}"); + assert!(area.contains(windows[0].min), "so it lies over the document area: {windows:?} in {area:?}"); +} + +/// The point a torn-off tab was released at is a point of the app window; the window it opens stands on the desktop +/// under that same point. +#[test] +fn a_tab_dropped_off_the_strip_opens_its_window_where_it_was_dropped() { + let window = app_window(); + let (mut app, ctx) = desktop(2, Some(window), 1.0); + assert_real_document_area(&app, window); + let document = app.session.documents()[1].doc.id; + let dropped = app.last_canvas_rect.min + egui::vec2(30.0, 12.0); + arranged(&mut app, &ctx, "floatInWindow", json!({ "document": document.0, "position": [dropped.x, dropped.y] })).expect("the torn-off tab floats"); + let windows = placed(&app); + assert_eq!(windows.len(), 1, "the drop opened one window"); + let want = dropped + window.min.to_vec2(); + assert!((windows[0].min - want).length() < 0.5, "the window opens under the point the tab was dropped at: {:?}, want {want:?}", windows[0]); +} + +#[test] +fn cascade_moves_every_window_into_the_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(3, Some(window), 1.0); + let area = area_on_desktop(&app, window); + arranged(&mut app, &ctx, "floatAllInWindows", json!({})).expect("every document gets a window"); + // One window the user dragged off the document area: Cascade brings it back, as it did before. + let size = app.ui.document_windows.floating[0].1.size(); + app.ui.document_windows.floating[0].1 = Rect::from_min_size(Pos2::new(2400.0, 1800.0), size); + arranged(&mut app, &ctx, "cascade", json!({})).expect("cascade runs"); + let windows = placed(&app); + assert!((windows[0].min - area.min).length() < 0.5, "the cascade starts at the document area's top-left: {windows:?}, the area is {area:?}"); + assert!(windows.iter().all(|rect| area.contains(rect.min)), "and every window lands over the document area: {windows:?} in {area:?}"); +} + +/// The docked layouts work in the app window's own points: a floating window's desktop place must not move the +/// document area the app draws in. +#[test] +fn the_docked_layouts_keep_the_window_s_own_document_area() { + let window = app_window(); + let (mut app, ctx) = desktop(2, Some(window), 1.0); + assert_real_document_area(&app, window); + let canvas = app.last_canvas_rect; + arranged(&mut app, &ctx, "twoUpVertical", json!({})).expect("2-up Vertical arranges the panes"); + assert_eq!(app.last_canvas_rect, canvas, "the layout leaves the app window's own document rect alone"); + let panes = crate::canvas::arranged_cells(&app, app.last_canvas_rect).expect("two panes"); + assert_eq!(panes.len(), 2, "one pane per document"); + for (document, pane) in &panes { + assert!(canvas.contains(pane.min) && canvas.contains(pane.max), "pane {document} stays inside the window's own points: {pane:?} in {canvas:?}"); + } + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let windows = placed(&app); + let first = windows.last().copied().expect("the floated window"); + assert!(area_on_desktop(&app, window).contains(first.min), "the floated window still opens over the document area: {first:?}"); + assert_eq!(app.last_canvas_rect, canvas, "and the document area did not move"); +} + +/// With no document open the app shows its empty desktop: no Arrange command opens a window there, and the desktop's +/// own layout is left as it is. +#[test] +fn an_empty_desktop_opens_no_window_and_keeps_its_layout() { + let window = app_window(); + let (mut app, ctx) = desktop(0, Some(window), 1.0); + let canvas = app.last_canvas_rect; + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("Float in Window over an empty desktop runs the framework arrangement"); + assert!(arranged(&mut app, &ctx, "floatInWindow", json!({ "position": [300.0, 200.0] })).is_err(), "a drop with no document behind it is refused"); + for command in ["floatAllInWindows", "newWindowForDocument", "cascade", "tile", "tileAllVertically"] { + let _ = arranged(&mut app, &ctx, command, json!({})); + } + assert!(app.ui.document_windows.floating.is_empty(), "no window opened over the empty desktop: {:?}", placed(&app)); + assert!(app.ui.document_windows.docked.is_empty(), "and no document group appeared"); + pass(&mut app, &ctx, Some(window), 1.0); + assert_eq!(app.last_canvas_rect, canvas, "the empty desktop keeps the layout it had"); +} + +/// Where the app window stands at the screen's origin its own points are desktop points: placement is what it was. +#[test] +fn a_window_at_the_screen_origin_places_where_it_always_did() { + let window = Rect::from_min_size(Pos2::ZERO, egui::vec2(1000.0, 720.0)); + let (mut app, ctx) = desktop(1, Some(window), 1.0); + assert_real_document_area(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - app.last_canvas_rect.min).length() < 0.5, "at the origin the window opens at the document area's own rect: {first:?}"); +} + +/// The desktop place is known once the host reports the app window's rect. Before that, and on the fallback layer +/// with no OS windows, the document area's own points are used as they are today. +#[test] +fn an_app_that_has_not_reported_its_place_keeps_todays_placement() { + let (mut app, ctx) = desktop(1, None, 1.0); + assert_real_document_area(&app, app_window()); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - app.last_canvas_rect.min).length() < 0.5, "with no rect reported the window opens where the document area is: {first:?}"); +} + +/// Where the host opens no OS window (egui embeds the viewports, as in the web build), the document window shows on +/// the framework's fallback layer inside the app window: its rect stays one of the app window's own points, and the +/// app window's desktop place is not added. +#[test] +fn a_document_window_on_the_fallback_layer_keeps_the_app_window_s_own_points() { + let window = app_window(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({ "width": 300, "height": 220, "name": "fallback.png" })).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + PhotocraftApp::setup_context(&ctx, Default::default()); + assert!(!craft::ui::runtime::windows::WindowHost::of(&ctx).viewports_available(), "this host opens no OS window of its own"); + for _ in 0..3 { + pass(&mut app, &ctx, Some(window), 1.0); + } + assert_real_document_area(&app, window); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!( + (first.min - app.last_canvas_rect.min).length() < 0.5, + "the fallback layer keeps the app window's own points: {first:?} in {:?}", + app.last_canvas_rect + ); +} + +/// The rule is in points, the unit the app window's rect and the document area are both reported in: the same place +/// at 100 %, 125 % and 200 % display scale. +#[test] +fn the_document_area_rule_holds_at_100_125_and_200_percent_scale() { + let window = app_window(); + let mut places: Vec = Vec::new(); + for scale in [1.0_f32, 1.25, 2.0] { + let (mut app, ctx) = desktop(1, Some(window), scale); + let area = area_on_desktop(&app, window); + assert!((area.min.x - (app.last_canvas_rect.min.x + window.min.x)).abs() < 0.5, "the area maps at {scale}: {area:?}"); + arranged(&mut app, &ctx, "floatInWindow", json!({})).expect("the active document floats"); + let first = placed(&app).pop().expect("one floating window"); + assert!((first.min - area.min).length() < 0.5, "at {scale} the window opens at the document area's top-left: {first:?}, the area is {area:?}"); + assert!((first.size() - area.size() * 0.5).length() < 0.5, "at {scale} the window's size is the same in points: {first:?} of {area:?}"); + places.push(first); + } + assert_eq!(places.len(), 3, "one place per scale"); + for pair in places.windows(2) { + assert!((pair[0].min - pair[1].min).length() < 0.5, "the scale does not move the window's place in points: {pair:?}"); + } +} diff --git a/crates/ui-egui/src/canvas/eyedropper_tool.rs b/crates/ui-egui/src/canvas/eyedropper_tool.rs index 163bb26948..730d6afac1 100644 --- a/crates/ui-egui/src/canvas/eyedropper_tool.rs +++ b/crates/ui-egui/src/canvas/eyedropper_tool.rs @@ -25,6 +25,10 @@ use crate::PhotocraftApp; #[path = "../eyedropper_cmyk_tests.rs"] mod cmyk_tests; +#[cfg(test)] +#[path = "other_precise_cursor_tests.rs"] +mod other_precise_cursor_tests; + /// The gesture's flags, kept in `CanvasTools::eyedropper`. #[derive(Debug, Default)] pub(crate) struct EyedropperState { @@ -44,6 +48,8 @@ pub(crate) struct PcEyedropper<'a> { stand_in: bool, /// Runs as a shape tool's Alt stand-in: a pick also sets the tool's Fill. shape_fill: bool, + /// The named Eyedropper uses a target for the Precise Other Cursors preference. + precise_target: bool, } /// The Eyedropper tool, for `Tool::Eyedropper`. @@ -68,7 +74,7 @@ impl<'a> PcEyedropper<'a> { let precise = app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise; (app.ui.tool_options.eyedropper, Srgba::rgb(r, g, b), precise, shape_alt_sets_fill(app.ui.tool)) }); - // Preferences › Cursors › Other Cursors = Precise wants the plain crosshair, so no ring. + // The sampling ring is the colour preview while held, separate from the pointer. options.show_ring &= !precise; let native = std::rc::Rc::new(std::cell::Cell::new(None)); let sampled_native = native.clone(); @@ -81,7 +87,15 @@ impl<'a> PcEyedropper<'a> { }) .map(|c| Srgba::rgb(c[0], c[1], c[2])) }; - PcEyedropper { scope, state, inner: EyedropperTool::new(options, sample).foreground(foreground), native, stand_in, shape_fill: stand_in && shape_fill } + PcEyedropper { + scope, + state, + inner: EyedropperTool::new(options, sample).foreground(foreground), + native, + stand_in, + shape_fill: stand_in && shape_fill, + precise_target: precise && !stand_in, + } } /// Writes the newest pick to its swatch; as a shape tool's stand-in, also makes the tool's Fill @@ -176,8 +190,10 @@ impl CanvasTool for PcEyedropper<'_> { self.inner.paint(draw, cx); } - /// `EyedropperTool::cursor`: the pipette, the precise crosshair with Caps Lock or the preference. fn cursor(&self, cx: &ToolContext<'_>) -> Cursor { + if self.precise_target && cx.precise() { + return super::cursor_policy::sample_target(); + } self.inner.cursor(cx) } diff --git a/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs b/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs new file mode 100644 index 0000000000..7b052b6947 --- /dev/null +++ b/crates/ui-egui/src/canvas/other_precise_cursor_tests.rs @@ -0,0 +1,75 @@ +//! The Other Cursors preference changes the Eyedropper over the document canvas. + +use craft::behavior::{Cursor, IconId, PaintedCursor}; +use craft::ui::primitives::painted_image; +use craft::ui::runtime::{env::Env, windows::WindowHost}; +use egui::Modifiers; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover}; +use crate::state::Tool; + +fn other_cursor(h: &mut Harness<'static, Box>, value: &str) { + h.state_mut().run("prefs.set", json!({"path": "cursors.other", "value": value})).unwrap(); +} + +fn pointer(h: &mut Harness<'static, Box>, mods: Modifiers) -> Cursor { + hover(h, 100.0, 150.0, mods); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()).expect("the tool cursor over the canvas") +} + +#[test] +fn precise_eyedropper_draws_a_centred_target() { + let mut h = harness(Tool::Eyedropper); + WindowHost::of(&h.ctx).set_caps_lock(Some(false)); + other_cursor(&mut h, "precise"); + let cursor = pointer(&mut h, Modifiers::NONE); + let Cursor::Painted(painted @ PaintedCursor::Circle { centre: true, .. }) = cursor else { + panic!("Precise Eyedropper should show a circle and crosshair, got {cursor:?}"); + }; + let bitmap = painted_image(&Env::of_root(&h.ctx), &painted, 2.0).expect("the target has a cursor bitmap"); + assert_eq!(bitmap.hotspot, bitmap.size.map(|side| side / 2), "the hotspot is the bitmap's centre"); + + let width = usize::from(bitmap.size[0]); + let [cx, cy] = bitmap.hotspot.map(usize::from); + let mut light_on_black = false; + let mut dark_on_white = false; + for (i, &[r, g, b, a]) in bitmap.rgba.as_chunks::<4>().0.iter().enumerate() { + // Sample off both axes so the contrast check uses the ring, away from the centre cross. + if (i % width).abs_diff(cx) <= 2 || (i / width).abs_diff(cy) <= 2 { + continue; + } + let alpha = f32::from(a) / 255.0; + let lightest = f32::from(r.max(g).max(b)); + let darkest = f32::from(r.min(g).min(b)); + light_on_black |= darkest * alpha >= 100.0; + dark_on_white |= lightest * alpha + 255.0 * (1.0 - alpha) <= 145.0; + } + assert!(light_on_black && dark_on_white, "the ring has a visible stroke on black and on white"); +} + +#[test] +fn standard_eyedropper_and_unaffected_tools_keep_their_cursors() { + let mut h = harness(Tool::Eyedropper); + let window = WindowHost::of(&h.ctx); + window.set_caps_lock(Some(false)); + let standard = pointer(&mut h, Modifiers::NONE); + assert!(matches!(&standard, Cursor::Painted(PaintedCursor::Tool { icon, .. }) if *icon == IconId::new("eyedropper"))); + window.set_caps_lock(Some(true)); + assert_eq!(pointer(&mut h, Modifiers::NONE), Cursor::Painted(PaintedCursor::Crosshair), "Caps Lock alone still uses the crosshair"); + other_cursor(&mut h, "precise"); + assert_eq!(pointer(&mut h, Modifiers::NONE), standard, "Caps Lock still inverts the preference"); + window.set_caps_lock(Some(false)); + + for tool in [Tool::Move, Tool::Type, Tool::Hand, Tool::Zoom] { + h.state_mut().ui.tool = tool; + other_cursor(&mut h, "standard"); + let standard = pointer(&mut h, Modifiers::NONE); + other_cursor(&mut h, "precise"); + assert_eq!(pointer(&mut h, Modifiers::NONE), standard, "{tool:?} keeps its cursor"); + } + h.state_mut().ui.tool = Tool::Brush; + assert_eq!(pointer(&mut h, Modifiers::ALT), Cursor::Painted(PaintedCursor::Crosshair), "the Alt stand-in keeps its cursor"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/arrange.rs b/crates/ui-egui/src/menus/view_cmds/arrange.rs index 6b34351e46..82242b89c9 100644 --- a/crates/ui-egui/src/menus/view_cmds/arrange.rs +++ b/crates/ui-egui/src/menus/view_cmds/arrange.rs @@ -42,18 +42,42 @@ pub(super) fn layout_checked(app: &PhotocraftApp, k: &str) -> Option { N_UP.contains(&k).then(|| app.ui.document_windows.arrangement == Some(arrangement)) } -/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). -fn screen_position(v: &Value) -> Option<[f32; 2]> { +/// Where the app window stands on the desktop, in desktop points. The app's own rects (the document area's) are in +/// the app window's points, while a document window that opens as an OS window opens at a desktop rect +/// (`DocumentWindow::first_placed` takes the outer rect in desktop points, and `follow_os_window` reads one back once +/// the user moved the window): this is the offset between the two. +/// Zero where the app shows its document windows on the fallback layer inside its own window, and where the host has +/// not reported the app window's rect yet (before its first pass): both keep today's placement. +/// One fallback this gate does not read: the framework also shows the layer inside the app window while OS windows are +/// available, when the app window itself is full screen or (on Wayland) maximized — `opens_over` in craft-libs +/// `ui-contract/src/runtime/windows.rs`. `WindowHost::opens_windows()` answers for the viewport of the running pass, +/// not for the app window, so a command run from the menu cannot decide that here; the offset is still added, and the +/// epic's #16846 is where full-screen modes with floating document windows are worked. +fn desktop_origin(app: &PhotocraftApp) -> egui::Pos2 { + let host = craft::ui::runtime::windows::WindowHost::of(app.ctx()); + if !host.viewports_available() { + return egui::Pos2::ZERO; + } + host.facts(egui::ViewportId::ROOT).map_or(egui::Pos2::ZERO, |facts| facts.inner.min) +} + +/// A finite `[x, y]` screen position within a sane range (window systems reject wild values). The point is one of the +/// app window's own points, where a torn-off tab was released, so it takes the same offset as the document area. +fn screen_position(v: &Value, app: &PhotocraftApp) -> Option<[f32; 2]> { const LIMIT: f64 = 1.0e6; let a = v.as_array().filter(|a| a.len() == 2)?; let n = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= LIMIT).map(|x| x as f32); - Some([n(0)?, n(1)?]) + let (x, y) = (n(0)?, n(1)?); + let origin = desktop_origin(app); + Some([x + origin.x, y + origin.y]) } /// The area and sizes the framework's arrangements work in: the document area, not the app's whole content. New /// windows take half of it; a window that follows its document's size is resized by `DocumentWindow` afterwards. pub(super) fn space(app: &PhotocraftApp) -> ArrangeSpace { - let area = app.last_canvas_rect; + // The framework places a new window on the desktop and cascades within this area, while the document area is a + // rect of the app window's own points: move it across by where the app window stands. + let area = app.last_canvas_rect.translate(desktop_origin(app).to_vec2()); let step = craft::ui::style::StyleCx::with_root(app.ctx(), |cx| cx.tokens.size.window.cascade); ArrangeSpace::new(area, area.size() * 0.5, step, app.session.active().map(|st| st.doc.id)) } @@ -102,7 +126,7 @@ fn float_in_window(app: &mut PhotocraftApp, p: &Value) -> Result }; let position = match p.get("position") { None | Some(Value::Null) => None, - Some(v) => Some(screen_position(v).ok_or("position must be [x, y] in points")?), + Some(v) => Some(screen_position(v, app).ok_or("position must be [x, y] in points")?), }; let space = space(app); // A document alone in a floating window keeps the window where it is. diff --git a/docs/releasing.md b/docs/releasing.md index 24da185b40..eda7a7fd30 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -128,7 +128,8 @@ are recorded in this procedure. Every binary reports its version, the commit and the build date: `photocraft --version`, `photocraft-cli --version`, and *Help › About PhotoCraft*. CI sets `PHOTOCRAFT_BUILD_SHA` and `PHOTOCRAFT_BUILD_DATE`, and `crates/engine-core/src/build_info.rs` reads them at compile time. A plain -`cargo build` doesn't set them and reports `0.2.0 (dev build)`. +`cargo build` doesn't set them and reports `0.2.0 (dev build)`; from a git checkout the desktop and CLI +build scripts add the commit, `0.2.0 (dev build, 3f2a9c1d0)` (a source tarball stays `(dev build)`). Every desktop build job (macOS, Windows, Linux, FreeBSD) also checks out [craft-fonts](https://github.com/storytold/craft-fonts) at the `craft-fonts-ref` commit in `.github/workflows/release.yml` and builds with `CRAFT_FONTS_DIR` and